Я создал простой класс Vector в JavaScript с конструктором и некоторыми методами. Метод add возвращает новый экземпляр Vector. При сравнении возвращаемого значения метода add с новым экземпляром, объявленным с такими же значениями, возвращается false
. Я также попытался изменить оператор равенства на двойное равенство, поэтому я считаю, что проблема не в ссылках.
class Vector {
constructor(components) {
this.length = components.length;
this.contents = components;
}
add(vector) {
if (this.length === vector.length) {
let a = [];
this.contents.forEach((cur, index) =>
a.push(cur + vector.contents[index])
);
return new Vector(a);
}
throw Error;
}
subtract(vector) {
if (this.length === vector.length) {
let a = [];
this.contents.forEach((cur, index) =>
a.push(cur - vector.contents[index])
);
return new Vector(a);
}
throw Error;
}
dot(vector) {
return this.contents.reduce(
(acc, cur, index) => (acc += cur * vector.contents[index]),
0
);
}
norm() {
return this.contents.reduce((acc, cur) => (acc += Math.pow(cur, 2)), 0);
}
equals(vector) {
return this.contents === vector;
}
toString() {
return this.contents.toString();
}
}
let a = new Vector([10, 20, 30]);
let b = new Vector([5, 15, 25]);
console.log(new Vector([15, 35, 55]));
console.log(a.add(b));
//Why does the log below return false?
console.log(new Vector([15, 35, 55]) === a.add(b));