gpt4 book ai didi

javascript - 具有相同内容的变量不相等......为什么?

转载 作者:行者123 更新时间:2023-11-28 11:57:51 25 4
gpt4 key购买 nike

如果两个变量内容相同,为什么我会收到 false?

function A() { return {k:'k'}; }
function B() { return {k:'k'}; }

var a = new A;
var b = new B;

var s='';

for (prop in a) {
if (typeof a[prop] != "function") {
s += "a[" + prop + "] = " + a[prop] + "; ";
}
}
alert(s);


for (prop in b) {
if (typeof b[prop] != "function") {
s += "b[" + prop + "] = " + b[prop] + "; ";
}
}
alert(s);


alert( a == b ); // false?

http://jsfiddle.net/wZjPg/

即使我为 a 和 b 分配相同的函数,也会发生同样的情况

var obj = {};

function A() { return {k:'k'}; }

var a = new A;
var b = new A;

alert( a == b ); // false?

http://jsfiddle.net/3rzrR/

这里也一样

k={zor:1};
b={zor:1};

alert(k==b); //false

http://jsfiddle.net/5v8BJ/

最佳答案

这是因为对象是通过引用进行比较的。

[] === []; // false

根据https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators ,

If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

关于javascript - 具有相同内容的变量不相等......为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19745855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com