return String vs Integer vs undefined vs null

Pie*_*rre 8 javascript

为什么javascript更喜欢返回String任何其他选择?

请考虑以下代码段.

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
Run Code Online (Sandbox Code Playgroud)

我故意调用一个不存在的数组元素.

但是我无法理解为什么会arr.item(43)返回String?为什么不nullundefined,甚至12

小智 25

因为this[x]undefined,这是假的,等等null.

||运算符返回第一个"truthy"价值发现,而在这一点上停止其评价.

如果未找到"truthy"值,则返回计算的最后一个操作数的结果.

总共有6个"假"值.他们是...

  1. false
  2. undefined
  3. null
  4. ""
  5. NaN
  6. 0

其他一切都被认为是真实的.

所以你的表达式将被评估为......

//   v--falsey            v--truthy! return it!
((((this[x] || null) || 'aïe') || 12) || undefined);
//               ^--falsey         ^--------^---these are not evaluated at all
Run Code Online (Sandbox Code Playgroud)

或者你可以像这样看待它:

(
  (
    (
      (this[x] || null) // return null
            /* (null */ || 'aïe') // return 'aïe' and stop evaluating
                                || 12) 
                                      || undefined);
Run Code Online (Sandbox Code Playgroud)

  • 只是一个挑剔,`||`返回最后一个评估表达式.在这种情况下,如果一个是*truthy*,它将返回. (2认同)

Ern*_*ill 5

该声明

return this[x] || null || 'aïe' || 12 || undefined ;
Run Code Online (Sandbox Code Playgroud)

将从左到右评估子表达式,并将返回未评估为false的第一个子表达式.不存在的元素由于未定义而求值为false,并且根据定义nullfalse.这使得字符串成为第一个非虚假子表达式,这就是你得到的.