This question already has answers here:
How to find the sum of an array of numbers
                                
                                    (41个回答)
                                
                        
                        
                            Multiply all elements in array
                                
                                    (4个答案)
                                
                        
                9个月前关闭。
            
        

我在函数(JavaScript)中动态输入了0到N项。

在每个位置都有类似items[1,3,4]的值,创建一个循环:

更新:项目或“数组”是动态的我没有永久值。

例如:for (var i = 0;i < items.length; i++){}

需要返回所有项目的乘积,只知道“ items.length”内部数组(for)的总数。

等等。需要累积

第二个可能在循环中每个相乘item[value] * item[value] *

第3个也许if(i == items.length){return total}(例如:1 * 3 * 4 = 12)

不知道如何累积 var total = item[value] * item[value] * ...

function **multiplyEach**(item){
  item[1,3,4]; //only ex.:this array have many possibilities of length
  for( var i = 0; i <= item.length; i++){
    var **items** = item[i] * item[i];
    if (i == item.length){
      return items;
    }
  }
}


在Chrome浏览器的调试中,项目具有NaN或未定义的值。 :/ ..

最佳答案

这是Array.prototype.reduce的好用例



const product = [1, 3, 4].reduce((product, n) => product * n, 1);

console.log(product);

10-06 04:22
查看更多