Javascript - 每个对数组中的每个int求和的乘法函数

问题描述 投票:-2回答:3

Javascript对我来说是新的,我们必须做功课。

我创建了新的数组:

var numbers = [1,2,3,4,5,6];

并且函数forEach我应该在console.log中实现结果:

console.log(numbers[0]*numbers[1]+numbers[0]+numbers[1]);

我测试了很多东西,但我不知道怎么拉出signle init ...

我知道它应该很简单,但我已经坚持了。感谢帮助!

javascript function loops foreach sum
3个回答
0
投票

从您的问题看起来您的问题正在与forEach循环的当前元素进行交互。

var numbers = [1,2,3,4,5,6]

// this will print every number in the array
// note that index numbers are not needed to get elements from the array
numbers.forEach(function(num){
  console.log(num)
})

现在,如果您要实现的是求和并乘以每个int(如问题标题中所述),您可以这样做

var numbers = [1,2,3,4,5,6]
var sumResult = 0
var multiplicationResult = 1

// the function will be evaluated for every element of the array
numbers.forEach(function(num){
  sumResult += num
  multiplicationResult *= num
})

console.log('Sum', sumResult)
console.log('Multiplication', multiplicationResult)

但是,使用qazxsw可以获得更合适的方法,我喜欢这样:

reduce

希望这可以帮助。

更多信息:

  • var numbers = [1,2,3,4,5,6] var sumResult = numbers.reduce(function(result, num){ return num+result }, 0) var multiplicationResult = numbers.reduce(function(result, num){ return num*result }, 1) console.log('Sum', sumResult) console.log('Multiplication', multiplicationResult)
  • Reduce @ MDN

0
投票

要为提供的数组提取单个数字,请使用索引器/括号表示法,该表示法在括号中指定数字(数组长度为1),如下所示:

ForEach @ MDN

要使用var numbers = [1, 2, 3, 4, 5, 6]; numbers[0]; // selects the first number in the array numbers[1]; // selects second number etc. 总结数字,只需:

forEach

var sum = 0; numbers.forEach(function(number) { sum += number; // add number to sum }); 遍历forEach数组中的所有数字,将每个数字传递给定义的函数,然后将数字添加到numbers变量。


0
投票

如果您需要结果,请使用sum。与map()不同,forEach()将始终以新数组返回结果。关于你期望使用什么表达式或者表达式的结果应该是什么,不是很清楚,所以这个演示将在每次迭代时执行以下操作:

  • A =当前值*下一个值
  • B =当前值+下一个值
  • C = A + B;

演示

map()
© www.soinside.com 2019 - 2024. All rights reserved.