if(negetive number) is true? Is something wrong with js?

后端 未结 4 1063
广开言路
广开言路 2021-01-26 18:52

Is something wrong with js?

if(\"hello\".indexOf(\"world\")) { // I forgot to add > -1 here
    console.log(\"hello world\");
}

Basically

4条回答
  •  礼貌的吻别
    2021-01-26 19:23

    The only number that is "falsey" (and would therefore evaluate to false and not pass an 'if' statement) is 0. The rest are "truthy", even negative ones.

    You can test this in the console with !!-1. That means converting the value to the Boolean opposite, and repeat once. The first ! on -1 returns false and the second returns true. This is the most common way to convert an expression to its Boolean equivalent.

提交回复
热议问题