从另一个数组中减去数组

Substract array from another array

本文关键字:数组 另一个      更新时间:2023-09-26

我有一个数组,里面有八个值。我有另一个具有相同数量值的数组。我可以简单地从彼此中减去这些数组吗?

下面是一个示例:

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..

应该如何正确完成此操作?

像这样:

var newArray = [];
for(var i=0,len=firstSet.length;i<len;i++)
  newArray.push(secondSet[i] - firstSet[i]);

请注意,secondSet应具有与firstSet相同(或更多)的数量

试一试:

for (i in firstSet) {
    firstSet[i] -= secondSet[i];
}

逐元素减法应该有效:

var result = [];
for (var i = 0, length = firstSet.length; i < length; i++) {
  result.push(firstSet[i] - secondSet[i]);
}
console.log(result);
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));​

你所追求的是类似于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