字符串与字符串的比较

Comparison String to String

我在下面得到了这两个例子 -

console.log("a" > "3") // 输出真

console.log("hello" > "3") // 输出真

根据MDNIf both values are strings, they are compared as strings, based on the values of the Unicode code points they contain

但他们在下一段中也写了以下内容,Strings are converted based on the values they contain, and are converted as NaN if they do not contain numeric values.

按照这个逻辑,不应该两个语句都是 false 因为不管它是什么运算符,“a”和“hello”都是字符串中的单词,它们没有数值,因此,它应该return NaN,而NaN是错误的;因此,只要其中一个操作数是 false,它就会输出 false?

如果我需要坚持上面的前一种说法,你能告诉我这个逻辑吗?

谢谢。

MDN 文章中的关键词是

If both values are strings, […].
Otherwise JavaScript attempts to convert non-numeric types to numeric values

所以不是,"a""3""hello"都是字符串,比较的时候,都是按字符串比较的。不会发生任何转换。

您正在比较两个字符串(在引号中),而不是字符串与数字。这应该可以回答您的问题:

"a" > "3" //true
"a" > 3 //false

如您所写,

If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain

因此,在这两个示例中,两个值都是字符串。如果将“3”改为3,则结果为:

console.log("a" > 3)
// expected output: false

console.log("hello" > 3)
// expected output: false

那是因为,先转换为NaN,然后​​:

If either value is NaN, the operator returns false.

文档:

If both values are strings, they are compared as strings, based on the values of the Unicode code points they contain.

Otherwise JavaScript attempts to convert non-numeric types to numeric values: ....

阅读文档,我了解到,如果两个字符串都有数值(都不是 NaN),那么它们都将被视为 Unicode 代码点。否则,如果两者都有数值,则将它们转换。

但是无论如何,我对 js 初学者的建议:现在不要太在意语言的工作方式,即使它 可以 将字符串与“更大”和“小于”,我认为不会(或不应该)存在您需要它的现实生活场景。

另外,好玩一下,看看我刚开始用js的时候做的this pen(我也很迷茫的比较和打字xD):

"" == null // this one is fun

稍后,在进一步了解这门语言之后,你就会明白为什么有些东西会像在 js 中那样工作,我还建议了解 js 和 web 的历史,它解释了该语言的许多奇怪行为.