Tony Hello
Tony Hello

Reputation: 69

why count++ doesn't increase in my situation

var count=0;

function showIt(){
    if(count==0){
        alert(count);
        count++;        
    }
    alert(count);

}

this function is an event of onclick, the first time I click the button, I got an alert 0 and 1, but when I continue clicked the statement which is "1" did not change. I have no idea why it does not change, I tried count=count+1, count +=1, none of them works.

Upvotes: 0

Views: 124

Answers (2)

KeV
KeV

Reputation: 2891

count++; is increasing your count variable.

The problem lies in your if statement which is if(count==0) , the first time count is zero, but afterwards count will be 1, hence not going into the body of the if statement and not incrementing count anymore.

Increment count outside of the if statement (don't move it to the else clause!).

Upvotes: 3

Popnoodles
Popnoodles

Reputation: 28409

Because you're only incrementing when count == 0

if(count==0){
    alert(count);
    count++;        
}

You mean

var count=0;

function showIt(){
    if(count==0){
        alert(count);
    }
    count++;        
    alert(count);
}
<button onclick="showIt()">showIt</button>

Upvotes: 5

Related Questions