关键词

javascript中比较字符串是否相等的方法

要比较JavaScript中的两个字符串是否相等,通常可以使用JavaScript提供的严格相等运算符===Object.is()方法。

使用严格相等运算符 ===

严格相等运算符===将比较两个字符串的值和类型。如果两个字符串的值和类型完全相同,则返回true,否则返回false

以下是使用===运算符比较字符串的示例代码:

const str1 = "hello";
const str2 = "Hello";
const str3 = "hello";

console.log(str1 === str2); // 返回false
console.log(str1 === str3); // 返回true

上面的代码中,我们定义了三个字符串变量srt1str2srt3。其中,str1str2的值不相同,因此使用===比较后返回false,而str1str3的值相同,因此使用===比较后返回true

使用Object.is()方法

Object.is()方法比较两个值是否相等,与===运算符相比,Object.is()方法在处理一些特殊情况时会更准确。

以下是使用Object.is()方法比较字符串的示例代码:

const str1 = "hello";
const str2 = "Hello";
const str3 = "hello";

console.log(Object.is(str1, str2)); // 返回false
console.log(Object.is(str1, str3)); // 返回true

上面的代码中,我们使用Object.is()方法比较了三个字符串,结果与使用===运算符比较的结果相同。

但是,当比较特殊值时,Object.is()方法的表现可能会与===运算符不同:

console.log(Object.is(NaN, NaN)); // 返回true
console.log(NaN === NaN); // 返回false

console.log(Object.is(+0, -0)); // 返回false
console.log(+0 === -0); // 返回true

上面的代码中,我们比较了NaN和+0/-0,结果与===运算符比较的结果不同。使用Object.is()方法时需要注意这些特殊情况。

本文链接:http://task.lmcjl.com/news/876.html

展开阅读全文