问题描述
为什么将数组与对应的字符串进行比较后将其评估为true?
Why is an array evaluated to true when it is compared to its corresponding string?
var a = [1,2,3];
var b = '1,2,3';
console.log(a==b);// true
变量a
存储为其分配的数组的内存地址.那么内存地址如何等于该数组的相应字符串.
Variable a
stores the memory address of the array it is assigned. Then how is a memory address equal to corresponding string of that array.
推荐答案
在出现"=="的情况下,数组将转换为toString
,然后由于松散比较而进行比较,因此它等于true.那么会发生什么:
Well in case of "==", array is converted to toString
and then compared due to loose comparison, so it equates to true. So what happens is this:
var a = [1,2,3];
var b = '1,2,3';
a == b //is same as
a.toString() === b //true
如果要在严格模式下评估为true,则还可以执行以下操作:
If you want to evaluate to true in a strict mode, you may also do something like this:
var a = [1,2,3];
var b = '1,2,3';
a = a.join(',')
console.log(b === a);
每当您比较宽松时(用'=='进行比较),javascript解释器都会尽力将这两个值转换为通用类型并进行匹配.要引用 MDN
Whenever you're loose comparing (with '=='), javascript interpreter tries it best to to convert both values to a common type and match them. To quote MDN
现在你的困惑是
a中存储的变量是数组的内存地址.因此,在第一个代码段中,您说a == b与a.toString == b相同,但是a中的内容是一个内存地址,因此当内存地址转换为字符串时,它与数组的对应字符串如何相等?
好吧,在比较两个变量时,请注意,您不是在比较它们的内存地址,而是在它们存储的值:)因此,不是内存地址被转换为toString
而是存储在它.
Well, note here when you comparing two variables, you're not comparing the memory address of them but the values stored at them :) So it's not the memory address that is getting converted to toString
but the value stored at it.
此外,这种想法还有一个缺陷.
Also, there's one more flaw in this thinking.
考虑,
var a = 4, // a holds address of variable a
b =4; //b holds the address of variable b
现在,这两个变量肯定持有不同的内存地址,因此它们不会等同于true
,这是不正确的.我希望你明白了.
Now, these two variables are definitely holding different memory addresses so they wouldn't have been equated to true
which is not true. I hope you got the point.
这篇关于为什么数组等于其对应的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!