简体   繁体   中英

JavaScript assignment and conditional on one line

I'm following some code in a HTML5 games book and can't understand how this line of code manages to work -

mp3Support = "" != audio.canPlayType('audio/mpeg');

I've worked out it means the same as -

if(audio.canPlayType('audio/mpeg') !=  "") {
    mp3Support = audio.canPlayType('audio/mpeg');
}

But I can't seem to wrap my head around how it's valid. How can you assign the mp3Support variable to an empty string, then test to see if it's not equal to something all on the same line? I've never come across this before and it's puzzling me.

mp3Support ends up being either true or false, as x != y returns true or false.

Same effect but shorter than writing

if(audio.canPlayType('audio/mpeg') !=  "") mp3Support = true;
else mp3Support = false;

mp3Support = "" != audio.canPlayType('audio/mpeg');

can be written as

mp3Support = ("" != audio.canPlayType('audio/mpeg'));

And that last part returns either true or false.

The != operator is not an assignment operator, it is a comparison operator . So on the right-hand side of the = (which is always executed before the = operator assigns a value), the code is comparing audio.canPlayType('audio/mpeg') 's return value with an empty string. If the return value is the empty string (or any other falsey value, but you should read the comparison operator link above for details on that), then the right-hand side of the = statement evaluates to false . Otherwise the right-hand side will evaluate to true . The boolean value resulting from that comparison is then assigned to mp3Support .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM