为什么这个函数 return 0

Why does this function return 0

我想弄清楚为什么 javascript 函数 returns 0this.position.startOffset 值是 0 而不是当值是数字时除了 0.

ready: function() {
    return (this.position.startOffset
            && this.position.endOffset
            && this.position.representation.trim().length >= 0
            && this.text.id
            && this.user.id
            && this.concept);
}

发生这种情况是由于 javascript 如何处理布尔表达式中的数字。 如果and(&&)语句中的第一个参数returns0,那么右边的参数不会被计算,返回0。

&& 链将在第一个非真实(虚假)值和 return 处停止评估。由于 0 是假的,因此遇到它时会被 returned。如果没有遇到虚假值,那么最后一个值为 returned:

var a = 55 && [] && 0 && false && true;     // yeild 0 as it is the first falsy value to encounter

console.log("a:", a);

var b = 30 && true && [] && "haha";         // yeild "haha" as it is the last value (no falsy value encountered)

console.log("b:", b);

虚假值是:

  1. null
  2. undefined
  3. 空字符串''""
  4. 人数0
  5. 布尔值false
  6. NaN