return String vs Integer vs undefined vs null [英] return String vs Integer vs undefined vs null
问题描述
为什么javascript更喜欢在任何其他选项中返回 String
?
Why does javascript prefers to return a String
over any other choices ?
请考虑以下代码段。
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)
返回 String
?为什么不 null
或 undefined
甚至 12
?
However i cannot understand why does arr.item(43)
returns the String
? Why not null
or undefined
or even 12
?
推荐答案
因为这个[x]
是 undefined
,这是假的,所以 null
。
Because this[x]
is undefined
, which is falsy, and so is null
.
||
运算符返回它找到的第一个truthy值,并在此时停止其评估。
The ||
operator returns the first "truthy" value it finds, and stops its evaluation at that point.
如果没有truthy值找到后,它返回最后一个被评估的操作数的结果。
If no "truthy" value is found, it returns the result of the last operand evaluated.
总共有6个假值。他们是......
There are a total of 6 "falsey" values. They are...
-
false
-
undefined
-
null
-
-
NaN
-
0
false
undefined
null
""
NaN
0
Everything else is is考虑到真实。
Everything else is considered truthy.
所以你的表达式将被评估为......
So your expression will be evaluated as...
// 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);
这篇关于return String vs Integer vs undefined vs null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!