我正在研究一个FCC中间算法 "Arguments Optional"。下面是需要发生的说明。
中间算法脚本 Arguments Optional
我写的代码做了上面解释的所有事情,但有一个要求是,参数必须都是数字,否则返回 undefined
(上文#4)。你会看到我写了一个三元运算符(我的代码的第5行) numbersOnly
变量,我认为它可以处理这个问题,但它只是在控制台中返回 [Function]。
function addTogether() {
// Convert args to an array
let args = [...arguments];
// Only accept numbers or return undefined and stop the program
const numbersOnly = value => typeof(value) === 'number'? value : undefined;
// test args for numbersOnly and return only the first two arguments regardless of the length of args
let numbers = args.filter(numbersOnly).slice(0, 2);
// // It has to add two numbers passed as parameters and return the sum.
if (numbers.length > 1) {
return numbers[0] + numbers[1];
}
// If it has only one argument then it has to return a function that uses that number and expects another one, to then add it.
else if (numbers.length === 1) {
let firstParam = numbers[0];
return function(secondParam) {
if (typeof secondParam !== 'number' || typeof firstParam !== 'number') {
return undefined;
}
return secondParam + firstParam;
}
}
}
我通过了所有的测试,除了#4,它应该返回未定义。我不太明白为什么5号测试通过并返回undefined,而4号测试却失败了。我在这里遗漏了什么?谢谢!我正在做一个FCC中间件。
1. addTogether(2, 3) should return 5.
2. addTogether(2)(3) should return 5.
3. addTogether("https://www.youtube.com/watch?v=dQw4w9WgXcQ") should return undefined.
4. addTogether(2, "3") should return undefined.
5. addTogether(2)([3]) should return undefined.
这是因为你必须从过滤器中检查输入参数和输出参数.尝试添加这个片段。
let numbers = args.filter(numbersOnly).slice(0, 2);
if (args.length > numbers.length) {
return undefined;
}
function addTogether() {
// Convert args to an array
let args = [...arguments];
// Only accept numbers or return undefined and stop the program
const numbersOnly = value => typeof(value) === 'number'? value : undefined;
// test args for numbersOnly and return only the first two arguments regardless of the length of args
let numbers = args.filter(numbersOnly).slice(0, 2);
if (args.length > numbers.length) {
return undefined;
}
// // It has to add two numbers passed as parameters and return the sum.
if (numbers.length > 1) {
return numbers[0] + numbers[1];
}
// If it has only one argument then it has to return a function that uses that number and expects another one, to then add it.
else if (numbers.length === 1) {
let firstParam = numbers[0];
return function(secondParam) {
if (typeof secondParam !== 'number' || typeof firstParam !== 'number') {
return undefined;
}
return secondParam + firstParam;
}
}
}
console.log('4. addTogether', addTogether(4, "4"));
因为当你过滤参数的时候,只有 '3'
被过滤掉,所以剩余数组的长度为1。
const args = [2, '3'];
const numbers = args.filter((n) => typeof n === 'number');
console.log('numbers:', numbers);
console.log('numbers.length === 1:', numbers.length === 1);