Javascript 返回字符串vs整数vs未定义vs null
为什么javascript比其他选择更喜欢返回Javascript 返回字符串vs整数vs未定义vs null,javascript,Javascript,为什么javascript比其他选择更喜欢返回字符串 考虑以下代码段 var arr = ['Hello1', 'Hello2', 'Hello3']; Array.prototype.item = function(x) { return this[x] || null || 'aïe' || 12 || undefined ; }; console.log( arr.item(43) ); // returns aïe 我故意调用了一个不存在的数组元素。 但是我不明白为什么arr
字符串
考虑以下代码段
var arr = ['Hello1', 'Hello2', 'Hello3'];
Array.prototype.item = function(x) {
return this[x] || null || 'aïe' || 12 || undefined ;
};
console.log( arr.item(43) ); // returns aïe
我故意调用了一个不存在的数组元素。
但是我不明白为什么
arr.item(43)
返回字符串
?为什么不null
或者undefined
或者甚至12
?因为这个[x]
是未定义的
,这是错误的,null
也是错误的
|
运算符返回它找到的第一个“truthy”值,并在该点停止计算
如果未找到“truthy”值,则返回最后计算的操作数的结果
总共有6个“错误”值。他们是
false
未定义
null
”
NaN
0
// v--falsey v--truthy! return it!
((((this[x] || null) || 'aïe') || 12) || undefined);
// ^--falsey ^--------^---these are not evaluated at all
或者你可以这样看:
(
(
(
(this[x] || null) // return null
/* (null */ || 'aïe') // return 'aïe' and stop evaluating
|| 12)
|| undefined);
(
(
(
(this[x]| | null)//返回null
/*(null*/| |'aïe')//返回'aïe'并停止计算
|| 12)
||未定义);
字符串是or链中的第一个真实值。简单。因为它是按从左到右的顺序计算的
如果要对此进行修改:
return this[x] || null || 12 || 'aïe' || undefined ;
你的答案是12。代码
a | | b
大致相当于a?a:b
,或者这个稍微详细一点的代码:
if (a) {
result = a;
} else {
result = b;
}
由于|
是表达式a | | b | | c
的计算结果为(a | | b)| c
因此,简单地说,这意味着链接时的
|
运算符返回第一个操作数,即“truthy”,或者返回最后一个元素
当缺少值时,此功能可用于提供默认值:
var result = f() || g() || defaultValue;
您可以这样理解:获取f()的结果。如果它是一个假值,那么尝试g()。如果它也给出了一个假值,那么使用defaultValue
语句
return this[x] || null || 'aïe' || 12 || undefined ;
将从左到右计算子表达式,并将第一个不计算为false的子表达式返回为false。不存在的元素计算为false,因为它未定义,
null
根据定义为false。这将保留字符串作为第一个非false子表达式,这就是您得到的结果。返回此[x]| | null | |‘a|e’| | 12 | | | | undefined
不会返回其中一个。它应该返回表达式this[x]的结果| | null | | | | e | 12 | | | |未定义
-我相信它会返回一个布尔值。只是吹毛求疵,|
返回最后一个计算的表达式。在这种情况下,当一个表达式为真时,它将返回该值。@alex:hmm…是的,但第一个“真的”表达式是最后计算的。也许我没有足够明确地强调短路。我会更新。斯蒂芬·科尔伯特会为这个答案的真实性感到自豪。