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

对着背影说爱祢 提交于 2019-12-12 02:14:27

问题


The same goes for '1\t' (and probably others).

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

回答1:


As said before if you compare number == string, it will automatically try to convert the string to a number. the \n and \t are simply whitespace characters and therefore ignored.

This and similar behaviour can be rather confusing leading to situations like this:

(Picture taken from: https://www.reddit.com/r/ProgrammerHumor/comments/3imr8q/javascript/)




回答2:


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 is of type Number hence '1\n' is converted to Number first then comparison takes place!

And Number() constructor will convert the string('1\n') to 1 :-

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

In Strict equality using ===, Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal.

Hence 1 === '1\n' will be expressed as false



来源:https://stackoverflow.com/questions/36619870/why-is-1-1-n-true-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!