问题
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