I have below code in 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));
This code outputs is -
false
false
how can I check whether the array includes the specific object is true?
asked Jul 24, 2019 at 23:10
2 Answers 2
Since it look like you're trying to check whether the objects contain the same values, see that you've already defined an equals
method - just use it:
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));
You can make the code more efficient by defining the method on the 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));
Also, keep in mind that 0.94924088690462316
holds too many significant figures for Javascript to handle - that number will be stored as 0.9492408869046232
:
console.log(0.94924088690462316);
answered Jul 24, 2019 at 23:13
Only slightly different from Snow's answer:
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));
var arr = [a1];
console.log(arr.some(abc => (a1.equals(abc))));
answered Jul 24, 2019 at 23:22
lang-js
true
because their properties and values are all the same?