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屋!