Pergunta

This loop breaks on the first time that it execute. Why.

<script>

for ( var i = 0; i < 10 ; i++ ) {

    console.log(i);

    if ( i = 5 ) {
        console.log (i);
        break;
    } 

}

</script>

output : 0 5

I'm expecting to : 0 1 2 3 4

Foi útil?

Solução

Use a double/triple comparison operator in the IF statement == or ===

<script>
    for ( var i = 0; i < 10 ; i++ ) {

        console.log(i);

        if ( i == 5 ) {
            console.log (i);
            break;
        } 

    }
</script>

Also, this will output 0 1 2 3 4 5 5. If you want the output to be 0 1 2 3 4, you should use the following code in place of the current IF statement.

if ( i == 4 ) {
    break;
} 

Outras dicas

You should use === instead of = in the if statement

<script>

for ( var i = 0; i < 10 ; i++ ) {

    console.log(i);

    if ( i === 5 ) {
        console.log (i);
        break;
    } 

}

</script>

The if evaluation is incorrect. Change it to...

if ( i == 5 )

Use i == 5 instead of i = 5 (assignment).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top