JavaScript OR(||)变量赋值说明 [英] JavaScript OR (||) variable assignment explanation
问题描述
给出这段JavaScript代码......
Given this snippet of JavaScript...
var a;
var b = null;
var c = undefined;
var d = 4;
var e = 'five';
var f = a || b || c || d || e;
alert(f); // 4
有人可以向我解释一下这种技术的用途(我的最佳猜测是在这个问题的标题!)?它是如何/为什么它正常工作?
Can someone please explain to me what this technique is called (my best guess is in the title of this question!)? And how/why it works exactly?
我的理解是变量 f
将被赋予第一个变量的最近值(从左到右)它的值不是null或未定义,但是我没有找到很多关于这种技术的参考资料,并且看到它使用了很多。
My understanding is that variable f
will be assigned the nearest value (from left to right) of the first variable that has a value that isn't either null or undefined, but I've not managed to find much reference material about this technique and have seen it used a lot.
此外,这种技术是否特定于JavaScript?我知道在PHP中做类似的事情会导致 f
有一个真正的布尔值,而不是 d
本身的值。
Also, is this technique specific to JavaScript? I know doing something similar in PHP would result in f
having a true boolean value, rather than the value of d
itself.
推荐答案
参见短路评估的解释。这是实现这些运营商的常用方式;它不是JavaScript独有的。
See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.
这篇关于JavaScript OR(||)变量赋值说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!