问题描述
我在某处看到了这段代码:
I saw somewhere this code snippet:
var idx = SOME_VALUE;
var color = {
yellor: 1,
red: 2,
black: 0
};
var x = color[idx] || []; // Is this means if color[idx] is null, then return an empty array?
我只能猜测代码 var x = color [idx] || [];
表示如果 color [idx]
为null,则返回一个空数组为x,否则为x = color [idx]。我是对的吗?
I can only guess the code var x = color[idx] || [];
means if color[idx]
is null, then return an empty array to x otherwise x= color[idx]. Am I right?
不过,我需要一个解释。此代码是否具有与以下相同的逻辑?
Still, I need an explaination. Does this code has the same logic as the following?
CONDITION==VALUE? TRUE_goes_here : FALSE_goes_here
推荐答案
这意味着如果 color [idx]
是falsy,而是使用空数组。 Falsy值 false
(当然), 0
, NaN
,,
undefined
, null
(所有其他值都是真实的)。这个成语是JavaScript的一个例子 *。
What it means is that if color[idx]
is "falsy," use an empty array instead. "Falsy" values are false
(of course), 0
, NaN
, ""
, undefined
, and null
(all other values are "truthy"). That idiom is an example of JavaScript's curiously powerful ||
operator*.
在这种情况下,如果 color 不包含名称包含在
idx
中的属性(因为当您索引这样的对象并且密钥与任何现有密钥不匹配时属性名称,结果是 undefined
): x
将 1
(如果 idx
是yellor), 2
(如果 idx
是红色), 0
(如果 idx
是黑色),或 []
如果 idx
是其他任何内容。
In this case, it's supplying a default value if color
doesn't contain a property with the name contained by idx
(because when you index into an object like that and the key doesn't match any existing property name, the result is undefined
): x
will be 1
(if idx
is "yellor"), 2
(if idx
is "red"), 0
(if idx
is "black"), or []
if idx
is anything else.
所以回答你的问题在你的问题的最后,基本上,是的。它是:
So answering your question at the end of your question, basically, yes. It's:
var x = color[idx];
if (!x) {
x = [];
}
或
var x = color[idx] ? color[idx] : [];
* (这是我的帖子)贫穷的小博客。)
这篇关于使用||的代码的确切含义是什么? (“OR”)运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!