开发者

javascript order of execution

var c = false;
if(c=[] && c.length==0)alert('hi');

hi is not alerted because c is still false when it executes the second operand of &&, can someone explain how the boolean operands in if condition are executed and in 开发者_运维问答what order?


I believe this is just a precedence issue - && is binding tighter than =. Your code is equivalent to:

if (c = ([] && c.length == 0))
{
    alert('hi');
}

So it's assigning c the value false rather than the empty array.

Try this instead:

if ((c = []) && c.length == 0)
{
    alert('hi');
}

EDIT: To address Tryptich's comment - I did try this before posting :) As CMS said, an empty array is considered true. Try this:

if (c = [])
{
    alert('empty array is true');
}

or even just this:

if ([])
{
    alert('empty array is true');
}

I checked the spec before posting - I was somewhat surprised that an empty array is considered true, but it is...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜