简体   繁体   English

JavaScript输入参数用空格分隔

[英]JavaScript input arguments separated with space

Today I've received couple recruitment tasks from one company. 今天,我已经收到一家公司的几份招聘任务。 They're pretty specific in those tasks that's why I'm wondering if I'm missing something. 它们在这些任务中非常具体,这就是为什么我想知道我是否缺少某些东西。 I got problem with one. 我有一个问题。 No matter what function should return, I know how to manage but here's how input looks: 无论应该返回什么函数,我都知道如何管理,但输入内容如下:

X X

x1 x2 x3... x1 x2 x3 ...

So big X is quantity of little x's. 因此,大X是小X的数量。 For example: 例如:

5 5

1 2 2 2 3 1 2 2 2 3

So how should I create a function taking X number of x's that operates on x's? 那么,我该如何创建一个以x的x个为单位对x进行运算的函数? What type should I expect as argument? 我应该期望哪种类型的参数?

Many thanks for your help! 非常感谢您的帮助!

You can either directly use an array or the rest parameter 您可以直接使用数组rest参数

For arrays, use myFunc , myFunc2 utilizes the rest parameter. 对于数组,请使用myFuncmyFunc2使用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

The expected result (in the console using the Array method) would be 预期的结果(在使用Array方法的控制台中)将是

5 // <- This is X (i.e. the amount of numbers)
1 // <- First number ...
2
2
2
3

I hope this is the answer to your question - otherwise please add more details. 希望这是您的问题的答案-否则,请添加更多详细信息。

I'd use the rest operator ( ... ) like such: 我将像这样使用rest运算符( ... ):

 const f = (...args) => `${args.length} items given: ${args.join(', ')}`; f(1, 2, 3, 5, 6); // 5 items given: 1, 2, 3, 5, 6 

If you're accepting a number as the required length of parameters being given, you could do something like this: 如果您接受数字作为给出的所需参数长度,则可以执行以下操作:

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM