Javascript:乘法和求和两个数组

时间:2022-10-11 12:02:06

I have two arrays of equal length, and I need to multiply the corresponding (by index) values in each, and sum the results.

我有两个相等长度的数组,我需要在每个数组中乘以相应的(按索引)值,并对结果求和。

For example

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];

would result in 34 (4*2+3*3+4*3+5*1).

会导致34(4 * 2 + 3 * 3 + 4 * 3 + 5 * 1)。

What's the simplest to read way to write this?

写这个最简单的方法是什么?

11 个解决方案

#1


10  

var sum = 0;
for(var i=0; i< arr1.length; i++) {
    sum += arr1[i]*arr2[i];
}

#2


7  

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];
console.log(arr1.reduce(function(r,a,i){return r+a*arr2[i]},0));
34

This shows the "functional" approach rather than the "imperative" approach for calculating the dot product of two vectors. Functional approach (which tends to be more concise) is preferred in such a simple function implementation as requested by the OP.

这显示了“功能”方法而不是用于计算两个向量的点积的“命令性”方法。在OP所请求的这种简单的功能实现中,优选功能方法(其趋于更简洁)。

#3


5  

Other answers are almost certainly more efficient, but just to give you a recursive viewpoint (it's nicer in some other languages). It does assume the two arrays are of equal length as you didn't specify what to do if they're not.

其他答案几乎肯定更有效,但只是为了给你一个递归的观点(它在其他一些语言中更好)。它确实假设两个数组的长度相同,如果它们没有指定该怎么做。

function sumProducts(array1, array2) {
    if(array1.length) 
        return array1.pop() * array2.pop() + sumProducts(array1, array2);

    return 0;
}

Edit:

katspaugh suggested flipping the returns which is ever so slightly more efficient (don't have to ! the length).

katspaugh建议翻转返回,这样的效率会更高一些(不必长度)。

#4


4  

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];


var result = 0;
for (var i=0; i < arr1.length; i++) {
  result += (arr1[i] * arr2[i]);
}

alert(result);

Try it here: http://jsfiddle.net/VQKPt/

在这里试试:http://jsfiddle.net/VQKPt/

#5


3  

var i, result = 0;
for(i = 0; i < arr1.length; i++)
    result += arr1[i]*arr2[i];
alert(result);

Not that this will cause an error if arr2 is shorter than arr1, but you said they're equal length, so I didn't bother checking for it.

如果arr2比arr1短,这不会导致错误,但是你说它们长度相等,所以我没有费心去检查它。

#6


3  

My vote for simplest-to-read way to write this goes to the humble for loop:

我最简单的阅读方式投票给谦卑的for循环:

var ii, sumOfProds = 0;
for (ii = 0; ii < arr1.length && ii < arr2.length; ii++) {
    sumOfProds += arr1[ii] * arr2[ii];
}

#7


3  

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];

a.map(function(x, index){ //here x = a[index]
 return b[index] + x 
});

=>[6,6,6,6,6]

//if you want to add the elements of an array:

a.reduce(function(x, y){
 return x + y
});

=>15

You can read about Array.map here. and Array.reduce here

你可以在这里阅读有关Array.map的内容。和Array.reduce在这里

#8


2  

Something like this:

像这样的东西:

var sum = 0;
for (var i=0, len = arr1.length; i < len; i++) {     // optimized looping
   sum += arr1[i] * arr2[i];
}

#9


2  

This seems pretty straight forward to me

这对我来说似乎很直接

var result=0;
for (var i=0; i<arr1.length;i++){
    result+=arr1[i]*arr2[i];   
}

#10


2  

Declare functions that does the operations you want.

声明执行所需操作的函数。

var sum      = function(a, b){ return a + b; };
var subtract = function(a, b){ return a - b; };
var multiply = function(a, b){ return a * b; };
var divide   = function(a, b){ return a / b; };

Then you have a very readable way to perform any operation on two arrays like this:

然后你有一个非常易读的方法在两个数组上执行任何操作,如下所示:

var array1 = [1,2,3];
var array2 = [2,4,8];

operateArrays(array1, array2, sum);      //[3, 6, 11]
operateArrays(array1, array2, subtract); //[-1, -2, -5]
operateArrays(array1, array2, multiply); //[2, 8, 24]
operateArrays(array1, array2, divide);   //[0.5, 0.5, 0.375]

Using this function

使用此功能

/**
* Divide each number of an array of numbers by another array of numbers
* @param  {Array}    arrayA  The array of numbers
* @param  {Array}    arrayB  The array of numbers
* @param  {Function} fn      Function that performs an operation
* @return {Array}            The resulting array
* @author Victor N. www.vitim.us
*/
function operateArrays(arrayA, arrayB, fn){
    if(arrayA.length!==arrayB.length) throw new Error("Cannot operate arrays of different lengths");
    return arrayB.map(function(b, i){
        return fn(arrayA[i], b);
    });
}

#11


0  

var arr = [1,2,3,4];
var arr2 = [1,1,1,2];

You can use:

您可以使用:

var squares = arr.concat(arr2).reduce((t,n)=>t+n);

or:

var squares = arr.map((a, i) => a + arr2[i]).reduce((t,n) => t+n);

console.log(squares);

#1


10  

var sum = 0;
for(var i=0; i< arr1.length; i++) {
    sum += arr1[i]*arr2[i];
}

#2


7  

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];
console.log(arr1.reduce(function(r,a,i){return r+a*arr2[i]},0));
34

This shows the "functional" approach rather than the "imperative" approach for calculating the dot product of two vectors. Functional approach (which tends to be more concise) is preferred in such a simple function implementation as requested by the OP.

这显示了“功能”方法而不是用于计算两个向量的点积的“命令性”方法。在OP所请求的这种简单的功能实现中,优选功能方法(其趋于更简洁)。

#3


5  

Other answers are almost certainly more efficient, but just to give you a recursive viewpoint (it's nicer in some other languages). It does assume the two arrays are of equal length as you didn't specify what to do if they're not.

其他答案几乎肯定更有效,但只是为了给你一个递归的观点(它在其他一些语言中更好)。它确实假设两个数组的长度相同,如果它们没有指定该怎么做。

function sumProducts(array1, array2) {
    if(array1.length) 
        return array1.pop() * array2.pop() + sumProducts(array1, array2);

    return 0;
}

Edit:

katspaugh suggested flipping the returns which is ever so slightly more efficient (don't have to ! the length).

katspaugh建议翻转返回,这样的效率会更高一些(不必长度)。

#4


4  

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];


var result = 0;
for (var i=0; i < arr1.length; i++) {
  result += (arr1[i] * arr2[i]);
}

alert(result);

Try it here: http://jsfiddle.net/VQKPt/

在这里试试:http://jsfiddle.net/VQKPt/

#5


3  

var i, result = 0;
for(i = 0; i < arr1.length; i++)
    result += arr1[i]*arr2[i];
alert(result);

Not that this will cause an error if arr2 is shorter than arr1, but you said they're equal length, so I didn't bother checking for it.

如果arr2比arr1短,这不会导致错误,但是你说它们长度相等,所以我没有费心去检查它。

#6


3  

My vote for simplest-to-read way to write this goes to the humble for loop:

我最简单的阅读方式投票给谦卑的for循环:

var ii, sumOfProds = 0;
for (ii = 0; ii < arr1.length && ii < arr2.length; ii++) {
    sumOfProds += arr1[ii] * arr2[ii];
}

#7


3  

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];

a.map(function(x, index){ //here x = a[index]
 return b[index] + x 
});

=>[6,6,6,6,6]

//if you want to add the elements of an array:

a.reduce(function(x, y){
 return x + y
});

=>15

You can read about Array.map here. and Array.reduce here

你可以在这里阅读有关Array.map的内容。和Array.reduce在这里

#8


2  

Something like this:

像这样的东西:

var sum = 0;
for (var i=0, len = arr1.length; i < len; i++) {     // optimized looping
   sum += arr1[i] * arr2[i];
}

#9


2  

This seems pretty straight forward to me

这对我来说似乎很直接

var result=0;
for (var i=0; i<arr1.length;i++){
    result+=arr1[i]*arr2[i];   
}

#10


2  

Declare functions that does the operations you want.

声明执行所需操作的函数。

var sum      = function(a, b){ return a + b; };
var subtract = function(a, b){ return a - b; };
var multiply = function(a, b){ return a * b; };
var divide   = function(a, b){ return a / b; };

Then you have a very readable way to perform any operation on two arrays like this:

然后你有一个非常易读的方法在两个数组上执行任何操作,如下所示:

var array1 = [1,2,3];
var array2 = [2,4,8];

operateArrays(array1, array2, sum);      //[3, 6, 11]
operateArrays(array1, array2, subtract); //[-1, -2, -5]
operateArrays(array1, array2, multiply); //[2, 8, 24]
operateArrays(array1, array2, divide);   //[0.5, 0.5, 0.375]

Using this function

使用此功能

/**
* Divide each number of an array of numbers by another array of numbers
* @param  {Array}    arrayA  The array of numbers
* @param  {Array}    arrayB  The array of numbers
* @param  {Function} fn      Function that performs an operation
* @return {Array}            The resulting array
* @author Victor N. www.vitim.us
*/
function operateArrays(arrayA, arrayB, fn){
    if(arrayA.length!==arrayB.length) throw new Error("Cannot operate arrays of different lengths");
    return arrayB.map(function(b, i){
        return fn(arrayA[i], b);
    });
}

#11


0  

var arr = [1,2,3,4];
var arr2 = [1,1,1,2];

You can use:

您可以使用:

var squares = arr.concat(arr2).reduce((t,n)=>t+n);

or:

var squares = arr.map((a, i) => a + arr2[i]).reduce((t,n) => t+n);

console.log(squares);