Typescript字符串与String.toLowerCase的比较奇数

Typescript String Comparison Oddity with String.toLowerCase

本文关键字:比较 toLowerCase 字符串 String Typescript      更新时间:2023-09-26

虽然很好奇(没有JS背景),但我开始深入Typescript,并面临着一堵砖墙。我想比较两个字符串,并使生活更容易,他们将首先对齐小写字母。这是代码:

let bool: boolean = false;
let i = 0;
this.comparisons[++i] = " init bool " + " => " + bool;
bool = false;
if ("a" == "a") { bool = true };
this.comparisons[++i] = ' "a" == "a" ' + " => " + bool;
bool = false;
if ("a" == "b") { bool = true };
this.comparisons[++i] = ' "a" == "b" ' + " => " + bool;
bool = false;
if ("a" == "A") { bool = true };
this.comparisons[++i] = ' "a" == "A" ' + " => " + bool;
bool = false;
if ("a".toLowerCase == "A".toLowerCase) { bool = true };
this.comparisons[++i] = ' "a".toLowerCase == "A".toLowerCase ' + " => " + bool;
bool = false;
if ("a".toLowerCase == "B".toLowerCase) { bool = true };
this.comparisons[++i] = ' "a".toLowerCase == "B".toLowerCase ' + " => " + bool;

并打印:

init bool => false
"a" == "a" => true
"a" == "b" => false
"a" == "A" => false
"a".toLowerCase == "A".toLowerCase => true
"a".toLowerCase == "B".toLowerCase => true

为什么最后一个表达式的求值结果为true?

"a"=="b"应该像第三条语句一样计算为false。

要调用方法,必须使用括号(),即使没有要传递给方法的参数:

bool = false;
if ("a".toLowerCase() == "B".toLowerCase()) { bool = true };

或者简单地说:

bool = ("a".toLowerCase() == "B".toLowerCase());

如果没有括号,"a".toLowerCase只是对String.toLowerCase方法本身的引用。比较的结果是true,因为它比较了两种方法,发现它们确实是相同的方法。