console.log("20">10); //true
console.log("20a">"10"); //true
console.log("20a">10); //false
我想知道为什么最后一个变成假。 并且“20a”转换为比较之前的内容。
最佳答案
来自 comparison operators 上的 MDN 页面:
For relational abstract comparisons (e.g. <=), the operands are first converted to primitives, then the same Type, before comparison.
console.log("20">10); //true
这会将 "20"
转换为数字 20
并进行比较。由于 20
大于 10
,因此为真。
console.log("20a">"10"); //true
这将比较两个字符串。由于 "20a"
大于(按字母顺序)"10"
,因此为真。
console.log("20a">10); //false
这会将 "20a"
转换为数字。结果是 NaN
(执行 +"20a"
以查看实际效果)。 NaN
不大于任何数字,因此返回 false。
关于javascript - 比较时字符串对象如何转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12855448/