[英]Javascript: Write a function that takes in a number, and returns an array with that number in it that many times
[英]Javascript function that takes any number of inputs and called multiple times and gives the result
我寫了這個解決問題的函數:
'use strict';
function myAdd(...args) {
let sum = 0;
const f = (...args2) => {
for (const val of args2) sum += val;
return f;
}
f.valueOf = () => sum;
return f(...args);
}
let sumFour = myAdd(2)(2);
console.log(+sumFour(2)); // expected 6
console.log(+sumFour(2)); //expected 6
但是,日志是:
console.log(+sumFour(2)); // outputs 6
console.log(+sumFour(2)); // outputs 8
我想我知道這個問題是每當函數 sumFour 被稱為 sum 正在被修改並且下一次被調用時它不再是 4 了。 我怎樣才能改變這個功能來解決這個錯誤?
您可以使用動態數量的參數調用函數。
如果你使用 ES5 運算符
function add() {
const args = Array.from(arguments);
return args.reduce((acc, cur) => acc + cur);
}
//console.log(add(3, 4, 5, 6, 7, 8, 10, 40)); // 33
如果你使用 ES6 擴展運算符
function sum(...args){
return args.reduce((acc, cur) => acc + cur);
}
//console.log(sum(3, 4, 5, 6, 7, 8, 10, 40)); // 33
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.