return String vs Integer vs undefined vs null [英] return String vs Integer vs undefined vs null

查看:53
本文介绍了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...


  1. false

  2. undefined

  3. null


  4. NaN

  5. 0

  1. false
  2. undefined
  3. null
  4. ""
  5. NaN
  6. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆