如果我们想创建一个函数实例(传入参数为数组),为其原型对象添加我们自定义的方法,实现两个数组对象对应的项进行相加、相减等。那我们应该怎么做呢?
我们想得到如下的效果:
var a = new Vector([1,2,3]);
var b = [3,4,5];
var c = [5,6,7,8];
console.log(a.add(b)); // should return [4,6,8]
console.log(a.subtract(b)); // should return [-2,-2,-2]
console.log(a.dot(b)); // should return 1*3+2*4+3*5 = 26
console.log(a.norm()); // should return sqrt(1^2+2^2+3^2)=sqrt(14)
console.log(a.add(c)); // should return false;(两个数组长度不一致)
my answer:
var Vector = function (components) {
this.value = components;
}
Vector.prototype = {
add: function (arr) {
var a = this.value;
if (a.length == arr.length) {
var newarr = [];
for (var i = 0; i < a.length; i++) {
newarr[i] = a[i]+arr[i];
}
return newarr;
} else {
return false;
}
},
subtract: function (arr) {
var a = this.value;
if (a.length == arr.length) {
var newarr = [];
for (var i = 0; i < a.length; i++) {
newarr[i] = a[i]-arr[i];
}
return newarr;
} else {
return false;
}
},
dot: function (arr) {
var a = this.value;
var b = arr.value;
if (a.length == arr.length) {
var sum = 0;
for (var i = 0; i < a.length; i++) {
sum += a[i]*arr[i];
}
return sum;
} else {
return false;
}
},
norm: function () {
var a = this.value;
var sum = 0;
for (var i = 0; i < a.length; i++) {
sum += a[i]*2;
}
return Math.sqrt(sum);
}
}