开发者

Multiple assignments inside if-statement

开发者 https://www.devze.com 2023-03-30 03:56 出处:网络
Why can\'t I do this: var fooElement, barElements; if(fooElement = document.getElementById(\'foo\') && barElements = fooElement.getElementsByTagName(\'bar\') && barE开发者_运维技巧lements[0] && barE

Why can't I do this:

var fooElement, barElements;
if(fooElement = document.getElementById('foo') && barElements = fooElement.getElementsByTagName('bar') && barE开发者_运维技巧lements[0] && barElements[0].onclick)
{
    console.log(barElements[0].onclick);
}

This won't work either:

var foo, bar;
if(foo = true && bar = true)
{
    console.log('yay');
}


Try this (it should give you a clue):

var foo, bar;
if((foo = true) && (bar = true))
{
    console.log('yay');
}


Check Operator Precedence,Use

if((foo = true) && (bar = true))
{
    alert(foo);
}

UPD: Don't forget that following code will not set bar to true because && is Short Circuit operator

if((foo = false) && (bar = true))
{
    alert(foo);
}

Sample

0

精彩评论

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