开发者

Array and if statements

if([]){}//true
if([]==t开发者_运维百科rue){}//false
if([1]==true){}//true
if([2]==true){}//false
if([1,2]==true){}//false
if(['Hi']==true){}//false
if([{aaa:1}]==true){}//false

[ ] is array. Array is object. Object is true, so [ ] is true. This is OK.

But I can't understand other results.


if([]){}//true

All JavaScript objects are truthy - they all coerce to the Boolean value true.


if([]==true){}//false

If one Operand is an Object, and the other operand is a Boolean, then both operands coerce to a Number value. An empty array will coerce to 0:

0 == 1 // false

if([1]==true){}//true

Same thing here. For an array with one item, that item will coerce to Number and that value will be compared to the other operand:

1 == 1 // true

if([2]==true){}//false

is:

2 == 1 // false

if([1,2]==true){}//false

If the array has multiple items, the coercion to Number will result in NaN:

NaN == 1 // false

if(['Hi']==true){}//false

The string coerces to the Number value NaN:

NaN == 1 // false

if([{aaa:1}]==true){}//false

An object also coerces to the Number value NaN:

NaN == 1 // false


if([]==true){}//false

[ ] is not a boolean true it's an array. That is saying that an empty array IS a boolean true. It isn't--it's an empty array.

if([]) {} evaluates it as being defined and not null.

Check this: http://11heavens.com/falsy-and-truthy-in-javascript


You can find some answers in here:

Strangest language feature

JavaScript equality transitivity is weird

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜