我有一个包含八个值的数组。我有另一个具有相同数值的数组。我可以简单地将这些数组相互减去吗?
以下是一个例子:
var firstSet =[2,3,4,5,6,7,8,9]
var secondSet =[1,2,3,4,5,6,7,8]
firstSet - secondSet =[1,1,1,1,1,1,1,1] //I was hoping for this to be the result of a substraction, but I'm getting "undefined" instead of 1..
如何妥善完成?
答案 0 :(得分:2)
像这样:
var newArray = [];
for(var i=0,len=firstSet.length;i<len;i++)
newArray.push(secondSet[i] - firstSet[i]);
请注意,secondSet
预计与firstSet
具有相同数量(或更多)
答案 1 :(得分:2)
尝试一下:
for (i in firstSet) {
firstSet[i] -= secondSet[i];
}
答案 2 :(得分:0)
元素减法应该有效:
var result = [];
for (var i = 0, length = firstSet.length; i < length; i++) {
result.push(firstSet[i] - secondSet[i]);
}
console.log(result);
答案 3 :(得分:0)
var firstSet = [2,3,4,5,6,7,8,9]
var secondSet = [1,2,3,4,5,6,7,8]
var sub = function(f, s) {
var st = [], l, i;
for (i = 0, l = f.length; i < l; i++) {
st[i] = f[i] - s[i];
}
return st;
}
console.log(sub(firstSet, secondSet));
答案 4 :(得分:0)
你所追求的是像Haskell的“zipWith”功能
“zipWith( - )xs ys”,或者在Javascript语法中“zipWith(function(a,b){return a - b;},xs,ys)”返回一个数组[(xs [0] - ys [0]),(xs [1] - ys [1]),...]
Underscore.js库为这类东西提供了一些很好的功能。它没有zipWith,但它确实有“zip”,它将一对数组xs,ys变成一对数组[[xs [0],ys [0]],[xs [1],ys [ 1]],...],然后您可以将减法函数映射到:
_.zip(xs,ys).map(function(x){return x [0] - x [1];})
您可能会发现这个有趣的https://github.com/documentcloud/underscore/issues/145