JavaScript矩阵添加任意数量的数组值,而无需使用array.map() [英] Javascript matrix addition of an arbitrary number of arrays' values, without using array.map()

查看:94
本文介绍了JavaScript矩阵添加任意数量的数组值,而无需使用array.map()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的AngularJS应用程序构建一个辅助函数(但解决方案不必使用 angular.forEach )。该函数应采用任意数量的具有相同长度的数组,并将这些值加在一起以形成一个新数组,例如:

I'm trying to build a helper function for my AngularJS app (but the solution doesn't have to use angular.forEach). The function should take an arbitrary number of arrays with same length and add the values together to form an new array, e.g.:

a = [1, 2, 3];
b = [4, 5, 6];
result = [5, 7, 9];

我正在尝试不使用array.map()或 sylvesterjs 以实现IE8兼容性。我一直在循环遍历参数,因为javascript似乎不喜欢在for循环中嵌套函数。到目前为止的代码:

I'm trying to not use array.map() or sylvesterjs for IE8 compatibility. I'm stuck on looping through arguments as javascript doesn't seem to like nesting functions within a for loop. Code so far:

function arrayAdd () {
  // make sure all args have same length
  var totalLen = 0;
  angular.forEach(arguments, function (arg) {
    totalLen += arg.length;
  });
  var avgLen = totalLen / arguments.length;

  if (avgLen === arguments[0].length) {
    var arrNew = mkArray(0, arguments[0].length);
    // helper function to make an empty array, not shown here

    // need to refactor below with loop for unlimited # of args
    angular.forEach(arguments, function (arg, i) {
      arrNew[0] += arg[0];
    });
    angular.forEach(arguments, function (arg, i) {
      arrNew[1] += arg[1];
    });

    return arrNew;
  } else {
    throw 'arrayAdd expects args with equal length';
  }
}

谢谢!

推荐答案

不需要映射,只需要对数组求和即可。

No need for map, you only need to keep track of the arrays as you total them.

(这不会检查数组的长度是否相同)。

(This does not check that the arrays have the same length-)

  function sumArrayElements(){
        var arrays= arguments, results= [], 
        count= arrays[0].length, L= arrays.length, 
        sum, next= 0, i;
        while(next<count){
            sum= 0, i= 0;
            while(i<L){
                sum+= Number(arrays[i++][next]);
            }
            results[next++]= sum;
        }
        return results;
    }

var a= [1, 2, 3], b= [4, 5, 6], c= [1, 2, 3];
sumArrayElements(a, b, c)
/* returned value:(Array)
6, 9, 12
*/

这篇关于JavaScript矩阵添加任意数量的数组值,而无需使用array.map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆