虽然好奇(并且没有 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
,因为它比较了两个方法,发现它们确实是同一个方法。
关于javascript - 使用 String.toLowerCase 进行 Typescript 字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36728302/