简体   繁体   中英

Adding JavaScript arrays vertically

I have 2 arrays =

var arr1 = ['20', '35', '50'];

var arr2 = ['+5', '-5', '+10'];

I need to add the elements vertically:

var finalArr = ['25', '30', '60'];

I tried:

var arr1 = ['20', '35', '50']
var arr2 = ['+5', '-5', '+10'];
for (var i = 0; i < arr1.length; i++) { 
var arr1 = arr1[i] + arr2[2];
}

You need to add the corresponding elements of the array, using the same index. You also need to assign the results either into the associated index in arr1 , or into a new array. Also, the array elements need to either be numbers in the first place, or you need to convert them into numbers within the loop. With them both being strings, you'll just concatenate them instead of adding them.

var arr1 = [20, 35, 50], arr2 = [5, -5, 10], finalArr = [];
for (var i = 0; i < arr1.length; i++) {
    finalArr.push(arr1[i] + arr2[i]);
}

One easy way to do this is by using eval creatively, like so:

var arr1 = ['20', '35', '50'];

var arr2 = ['+5', '-5', '+10'];

var result = arr1.map(function(e,i){
    return eval(e+arr2[i]);
});

Or if you don't want to use eval then you can do simply parse string, parsing to int doesn't ignore the sign.

arr1.map(function(e,i){
    return +(e)+(+arr2[i]);
});

http://jsfiddle.net/mjbwbzof/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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