今天,我收到了一家公司的几个招聘任务。它们在这些任务中非常具体,这就是为什么我想知道我是否遗漏了什么。我对其中一个有意见。不管应该返回什么函数,我都知道如何管理,但下面是输入的样子:
X
x1 x2 x3...
因此大X是小x的数量。例如:
5
1 2 2 2 3
那么,我应该如何创建一个函数,该函数采用X个数的x来对x进行运算呢?我应该期望哪种类型的参数?
非常感谢您的帮助!
发布于 2019-07-09 00:01:06
您可以直接使用array或rest parameter
对于数组,使用myFunc,myFunc2使用rest参数。
// ARRAY AS SINGLE PARAMETER
function myFunc(numbers) {
for (var i of numbers) {
console.log(i); // Do whatever you like to do here
}
}
// REST PARAMETER
function myFunc2 (X, ...xs) {
console.log(X); // The number of arguments
for (i of xs) {
console.log(i); // One argument per iteration
}
}
var xarr = [1, 2, 2, 2, 3];
var X = xarr.length; // X is 5
console.log(X);
myFunc(xarr); // Passes the numbers as an array to your function.
myFunc2(5, 1, 2, 3, 4, 5); // Uses the rest parameter预期的结果(在控制台中使用Array方法)将为
5 // <- This is X (i.e. the amount of numbers)
1 // <- First number ...
2
2
2
3我希望这是您问题的答案-否则请添加更多详细信息。
发布于 2019-07-09 00:07:44
我会像这样使用rest运算符(...):
const f = (...args) => `${args.length} items given: ${args.join(', ')}`;
f(1, 2, 3, 5, 6); // 5 items given: 1, 2, 3, 5, 6
发布于 2019-07-09 00:14:10
如果您接受一个数字作为给定参数的所需长度,您可以这样做:
let x = n => (arr) => (arr.length === n) ? arr.toString() : "Invalid Size";
let x = n => (arr) => (arr.length === n) ? arr.toString() : "Invalid Size";
let a = x(5)([1,2,3,4]), b = x(5)([1,2,3,4,5]);
console.log(a,b);
https://stackoverflow.com/questions/56938522
复制相似问题