简体   繁体   English

Javascript:两个数组相乘和求和

[英]Javascript: Multiply and Sum Two Arrays

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?写这个最简单的阅读方式是什么?

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 要求的如此简单的函数实现中,函数方法(往往更简洁)是首选。

var sum = 0;
for(var i=0; i< arr1.length; i++) {
    sum += arr1[i]*arr2[i];
}
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 .您可以在此处阅读有关 Array.map 的信息 and Array.reduce here和 Array.reduce 在这里

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 建议翻转返回的效率,这样效率更高(不必!长度)。

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/

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 短,这会导致错误,但是您说它们的长度相等,所以我没有费心检查它。

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];
}
function mul (arr1, arr2) {
    var n_array = (arr1,arr2).map(x => x * x)
    return n_array
    }
var a = [1,2,3]
var b = [1,2,3]
console.log(mul(a,b))

Something like this:像这样的东西:

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

This seems pretty straight forward to me这对我来说似乎很直接

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

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);
    });
}
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);

使用 ES6 .reduce() 的单行解决方案:

const sum_products = arr1.reduce((sum, val, i) => sum + (val * arr2[i]), 0)

Here are 3 functions that all accomplish the same thing.这里有 3 个函数,它们都完成相同的事情。 They are listed in order of increasingly modern JavaScript syntax.它们是按照越来越现代的 JavaScript 语法的顺序列出的。

The first function uses basic language features that have been around since the beginning.第一个函数使用从一开始就存在的基本语言特性。 This will work on really old browsers such as IE6.这将适用于非常旧的浏览器,例如 IE6。

The second function uses features from ECMASScript 5 which was introduced around 2009, and will work on IE9+.第二个函数使用了 2009 年左右推出的 ECMASScript 5 的功能,并将在 IE9+ 上运行。

The third function uses ECMASScript 2015 arrow functions and will not work on any version of IE, not even IE 11 unless you are using some type of build-step in your code to transpile down to ES5 like Babel or Typescript第三个函数使用 ECMASScript 2015 箭头函数,不适用于任何版本的 IE,甚至 IE 11 也不行,除非您在代码中使用某种类型的构建步骤来转换为 ES5,如 Babel 或 Typescript

/**
 * Multiplies the corresponding values of two arrays and then sums the product.
 * Supported in all legacy browsers
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMAScript4(arr1, arr2) {
    var total = 0;
    for(var i = 0; i < arr1.length; i += 1) {
        total += arr1[i] * arr2[i];
    }
}

/**
 * Multiplies the corresponding values of two arrays and then sums the product.
 * Supported in all mainstream browsers except IE 8 and older.
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMASScript5(arr1, arr2) {
    // The map function creates a new array of the product of arr1 and arr2 values
    // The reduce function then takes this array of products and adds up all the values
    return arr1
        .map(function (value, index) { return value * arr2[index]; })
        .reduce(function (sum, current) { return sum + current; }, 0);
}

/**
 * Multiplies the corresponding values of two arrays and then sums the product.
 * Supported in all mainstream browsers except IE.
 * @param {number[]} arr1 The first array
 * @param {number[]} arr2 The second array
 **/
function sumOfProductsECMASScript2015(arr1, arr2) {
    // The map function creates a new array of the product of arr1 and arr2 values
    // The reduce function then takes this array of products and adds up all the values
    return arr1
        .map((v, i) => v * arr2[i])
        .reduce((sum, v) => sum + v, 0);
}



// Define your arrays
let arr1 = [2,3,4,5];
let arr2 = [4,3,3,1];

// Usage
let answer = sumOfProductsECMASScript4(arr1, arr2);
let answer2 = sumOfProductsECMASScript5(arr1, arr2);
let answer3 = sumOfProductsECMASScript2015(arr1, arr2);

if you were doing much of this kind of thing, you would probably use a library like mathjs :如果你做了很多这类事情,你可能会使用像mathjs这样的库:

var arr1 = [2,3,4,5];
var arr2 = [4,3,3,1];
result=math.dot(arr1,arr2);

make it map and reduce使其映射并减少

 var arr1 = [2,3,4,5]; var arr2 = [4,3,3,1]; var result = arr1.map((v,i) => v * arr2[i]).reduce((x, y) => x + y, 0) console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM