簡體   English   中英

JavaScript輸入參數用空格分隔

[英]JavaScript input arguments separated with space

今天,我已經收到一家公司的幾份招聘任務。 它們在這些任務中非常具體,這就是為什么我想知道我是否缺少某些東西。 我有一個問題。 無論應該返回什么函數,我都知道如何管理,但輸入內容如下:

X

x1 x2 x3 ...

因此,大X是小X的數量。 例如:

5

1 2 2 2 3

那么,我該如何創建一個以x的x個為單位對x進行運算的函數? 我應該期望哪種類型的參數?

非常感謝您的幫助!

您可以直接使用數組rest參數

對於數組,請使用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

預期的結果(在使用Array方法的控制台中)將是

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

希望這是您的問題的答案-否則,請添加更多詳細信息。

我將像這樣使用rest運算符( ... ):

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

如果您接受數字作為給出的所需參數長度,則可以執行以下操作:

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