简体   繁体   中英

Javascript array store each value in variable

How can I store each value of javascript array in variable such that I can use it to perform further actions?

Eg:

var plan = [100, 200];
var months = [3, 6];

for (var i = 0; i < plan.length; i++) {
    p_det = plan[i];
}
for (var i = 0; i < months.length; i++) {
    m_det = months[i];
}
console.log(p_det * m_det); //Gives me value of 200*6 

Mathematical action I've to perform such that ((100 * 3) + (200 * 6))

Is storing each value in variable will help? How can I achieve this?

Storing each element in a variable won't help, you already can access those values using the array[index]. Assuming your arrays are the same length, you can calculate what you want in a loop:

for (var sum = 0, i = 0; i < plan.length; i++) {
    sum += plan[i]*month[i];
}
console.log( sum );

you can achieve it with reduce assuming that both arrays have same length

 var plan = [100, 200]; var months = [3, 6]; var sum = plan.reduce(function(sum, val, index) { return sum + months[index] * val; }, 0); snippet.log(sum) 
 <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 

A simple while loop will do. It works for any length, because of the Math.min() method for the length.

 function s(a, b) { var i = Math.min(a.length, b.length), r = 0; while (i--) { r += a[i] * b[i]; } return r; } document.write(s([100, 200], [3, 6])); 

In ES6:

sum(plan.map((e, i) => e * months[i])

where sum is

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

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