gpt4 book ai didi

javascript - 如何检查对象数组是否包含 Node 中的特定对象

转载 作者:行者123 更新时间:2023-11-30 08:18:58 25 4
gpt4 key购买 nike

我在 Node 中有以下代码-

function ABC(a,b,c) {
this.a = a;
this.b = b;
this.c = c;
this.equals = function(other) {
return other.a == this.a &&
other.b == this.b &&
other.c === this.c;
};
}

var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);

console.log(a1 === a2);
var arr = [a1];
console.log(arr.includes(a2));

这段代码输出是-

 false
false

如何检查数组是否包含特定对象?

最佳答案

因为看起来您正在尝试检查对象是否包含相同的值,请注意您已经定义了一个 equals 方法 - 只需使用它:

function ABC(a,b,c) {
this.a = a;
this.b = b;
this.c = c;
this.equals = function(other) {
return other.a == this.a &&
other.b == this.b &&
other.c === this.c;
};
}

var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);

console.log(a1.equals(a2));

您可以通过在原型(prototype)上定义方法来提高代码的效率:

function ABC(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}

ABC.prototype.equals = function(other) {
return other.a == this.a &&
other.b == this.b &&
other.c === this.c;
};

var a1 = new ABC("1", "1", 0.94924088690462316);
var a2 = new ABC("1", "1", 0.94924088690462316);

console.log(a1.equals(a2));

此外,请记住 0.94924088690462316 包含太多重要数字,Javascript 无法处理 - 该数字将存储为 0.9492408869046232:

console.log(0.94924088690462316);

关于javascript - 如何检查对象数组是否包含 Node 中的特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192361/

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