简体   繁体   中英

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

x1 x2 x3...

So big X is quantity of little x's. For example:

5

1 2 2 2 3

So how should I create a function taking X number of x's that operates on x's? What type should I expect as argument?

Many thanks for your help!

You can either directly use an array or the rest parameter

For arrays, use myFunc , myFunc2 utilizes the rest parameter.

// 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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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