javascript - 使用 String.toLowerCase 进行 Typescript 字符串比较

标签 javascript typescript

虽然好奇(并且没有 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/

相关文章:

JavaScript/jQuery 简写函数定义

javascript - jQuery 将数据发送到 webapi

javascript - IONIC 3 中的 setInterval

javascript - 如何处理 Meteor 中的客户端对象?

javascript - 如何使用 jquery 检测下拉列表中的选项内容变化?

sql - 如何在 TypeORM 迁移中指定列名大小写

javascript - Angular 2 注入(inject)器层次结构和 NgModule

typescript - Primeng日历: Set date from database

javascript - 在 gulp 中运行 ng build 使用旧版本的 node.js

javascript - 位置 0 出现意外标记 b