为什么 1 == '1\n' 在 Javascript 中为真?

Why is 1 == '1\n' true in Javascript?

'1\t'(可能还有其他)也是如此。

if (1 == '1\n') {
  console.log('Equal');
}
else {
  console.log('Not Equal');
}

The equality operator(==) converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

1 是类型 Number 因此 '1\n' 首先转换为 Number 然后 comparison 发生!

Number() 构造函数会将字符串 ('1\n') 转换为 1 :-

Number('1\n') === 1

Strict equality using === 中,两个值在比较之前都不会隐式转换为其他值。如果值有不同的类型,则认为值不相等。

因此1 === '1\n'将表示为false

如前所述,如果您比较 number == string,它会自动尝试将字符串转换为数字。 \n\t 只是空白字符,因此会被忽略。

这种行为和类似的行为可能会导致出现如下情况:

(图片取自:https://www.reddit.com/r/ProgrammerHumor/comments/3imr8q/javascript/