[英]JavaScript strict type checking fails
I was checking three Strings equality;我正在检查三个字符串是否相等;
var str1 = "Hello World!";
var str2 = "Hello \
World!";
var str3 = "Hello" + " World!";
//console.log(str1===str2);//true
// console.log(str2===str3);//true
console.log(str1 === str2 === str3); //false
How can we check this scenario where I want to compare 3 variables?我们如何检查我想比较 3 个变量的情况?
Your question isn't totally clear to me.你的问题对我来说并不完全清楚。
With和
console.log(str1 === str2 === str3);
you're checking你在检查
(str1 === str2) === str3
(yes, the associativity is left to right here) (是的,结合性在这里从左到右)
That is, you're comparing a boolean to a string.也就是说,您将布尔值与字符串进行比较。
What you want is你想要的是
(str1 === str2) && (str2 === str3)
Then the best would be to normalize your strings using a function like那么最好的方法是使用类似的函数来规范化你的字符串
function normalize(str){
return str.replace(/\s+/g,' ');
}
And you can define a function comparing all your strings:您可以定义一个比较所有字符串的函数:
function allEquals(strs) {
var p;
for (var i=0; i<arguments.length; i++) {
if (typeof arguments[i] !== "string") return false;
var s = arguments[i].replace(/\s+/g, ' ');
if (p !== undefined && s!==p) return false;
p = s;
}
return true;
}
console.log(allEquals(str1, str2, str3));
Note: multi-line string literals are painful.注意:多行字符串文字很痛苦。 Those strings are different:这些字符串是不同的:
var str2 = "Hello \
World!";
var str4 = "Hello \
World!";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.