ES6其余参数代码不起作用

时间:2018-08-02 21:57:44

标签: javascript

为什么此代码不求和? 我正在尝试使用javascript ... rest参数

function sum(...nums) {  
  let total = 0;  
  for(const num of nums) {  
    total += num;  
  }  
  return total;  
}   

sum(10, 36, 7, 84, 90, 110);

2 个答案:

答案 0 :(得分:2)

您的代码运行正常。您实际上并没有在任何地方输出结果:

function sum(...nums) {
  let total = 0;  
  for(const num of nums) {  
    total += num;  
  }  
  return total;  
}   

let res = sum(10, 36, 7, 84, 90, 110);

console.log(`Total: ${res}`);

答案 1 :(得分:0)

您的代码很棒,但是您什么也不输出:)

const sum = (nums) => [...nums].reduce((x, y) => x + y, 0)

const nums = [10, 36, 7, 84, 90, 110]

const result = sum(nums)

console.log(result)