【问题标题】:Javascript - Function for each which sums and multiplies every int in arrayJavascript - 每个函数对数组中的每个 int 求和并相乘
【发布时间】:2017-12-23 17:59:11
【问题描述】:

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

我创建了新数组:

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

使用 forEeach 函数,我应该可以达到 console.log 中的结果:

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

我已经测试了很多东西,但我不知道如何取出signle init...

我知道它应该很简单,但我卡住了。 感谢您的帮助!

【问题讨论】:

标签: javascript function loops foreach sum


【解决方案1】:

从您的问题看来,您的问题与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)

但是,可以通过像这样使用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)

希望这会有所帮助。

更多信息:

【讨论】:

  • 为什么不let { sum, product } = numbers.reduce((o, n) => (o.sum += n, o.product *= n, o), { sum: 0, product: 1 })
  • 完全有效!然而,正如提问者所说,对 JS 来说是新手,不想通过添加对象或 ES6 语法来增加答案的复杂性
【解决方案2】:

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

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 数组中的所有数字,将每个数字传递给定义的函数,然后将该数字添加到sum 变量中。

【讨论】:

    【解决方案3】:

    如果您想要您的结果,请使用map()。与forEach() 不同,map() 将始终以新数组的形式返回结果。关于您应该使用什么表达式或该表达式的结果应该是什么并不是很清楚,因此该演示将在每次迭代中执行以下操作:

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

    演示

    const num = [1, 2, 3, 4, 5, 6];
    
    let arr = num.map(function(n, idx, num) {
      let next = num[idx + 1];
      if (!next > 0) {
        next = idx + 2;
      }
      let subSUM = n + next;
      let subPRD = n * next;
      let subRES = subPRD + subSUM;
      return subRES;
    
    });
    
    console.log(arr);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多