我已经在JavaScript中使用构造函数和一些方法创建了一个简单的Vector类。 add方法返回一个新的Vector实例。将add方法的返回值与用相同值声明的新实例进行比较时,将返回false
。我也尝试过将相等运算符更改为double equals,因此我认为问题与引用无关。
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));
[使用===
比较数组时,您正在比较它们的地址。签出:
> a = [1,2]
[ 1, 2 ]
> b = [1,2]
[ 1, 2 ]
> a === b
false
如果数组包含相同的元素,则需要迭代。
顺便说一句,您还应该写throw **new** Error()
。