目前我正在开发 freeCodeCamp
challenge 。我宁愿复制/粘贴挑战本身,也不愿自己写。
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, addTogether(2, 3) should return 5, and addTogether(2) should return a function.
Calling this returned function with a single argument will then return the sum:
var sumTwoAnd = addTogether(2);
sumTwoAnd(3) returns 5.
If either argument isn't a valid number, return undefined.
这是我创建的解决方案:
function addTogether(a) {
for (let j = 0; j < arguments.length; j++){
// console.log(typeof(arguments[j]));
if(typeof(arguments[j]) != "number"){
return undefined;
} else if (typeof(arguments[j]) == 'string') {
return undefined;
} else {
console.log('go up');
if (arguments.length >= 2){
let sum = 0;
for(let i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
}
}
return function(b){
if (typeof(b) == 'object'){
return undefined;
} else {
return a + b;
}
}
}
这个解决方案的正确率是 80%,但它无法处理 addTogether(2, "3") 应该返回未定义的情况。
尽管我添加了此检查 typeof(arguments[j] ) == '字符串'
。我该如何让它发挥作用?谢谢。
最佳答案
尝试调用addTogether()
function addTogether(a, b) {
if(typeof(a) !== 'number' || (b != undefined && typeof(b) !== 'number')) {
return undefined;
}
if(b == undefined) {
return c => addTogether(a, c);
}
return a + b;
}
addTogether(2,3);
关于javascript - 参数可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60864666/