简体   繁体   English

Javascript - 将数组中的元素与其位置相乘

[英]Javascript - multiply elements in an array by their position

How can I multiply the elements in an array by their positions in the array?如何将数组中的元素乘以其在数组中的位置?

For example,例如,

I want to take the elements in this array我想取这个数组中的元素

var multiply = [2, 4, 6, 7]

and essentially come out with ( 2*1+4*2+6*3+7*4 ).基本上出来了( 2*1+4*2+6*3+7*4 )。

I understand that I need to use a for loop but I don't know how to write it to get that result.我知道我需要使用 for 循环,但我不知道如何编写它以获得该结果。

Thank you!谢谢!

Do it like this, but try to understand how it works:这样做,但尝试了解它是如何工作的:
I have replaced the old values in the array.我已经替换了数组中的旧值。
So multiply changed into the new values in this example.因此, multiply更改为本示例中的新值。

 var multiply = [2, 4, 6, 7]; multiply.forEach(function(e, i) { multiply[i] = e * ++i; }) document.write(JSON.stringify(multiply)); // output: [2,8,18,28]

You could use the following:您可以使用以下内容:

multiply.map(function(v, i){
  return v * (i+1);
});

You can assign it to a variable or do whatever you need with this (since a new array is returned).您可以将它分配给一个变量或使用它执行任何您需要的操作(因为返回了一个新数组)。

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

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