簡體   English   中英

我可以繞過可選參數而仍然在Javascript中設置rest參數嗎?

[英]Can I bypass optional parameters and still set a rest parameter in Javascript?

我有一個帶有必需參數(A),一些可選參數(B,C)和其他參數(Z)的函數

const doTheThing = (a, b = 'B', c = 'C', ...z) => {
  console.log(a, b, c, z);
}

在某些情況下,我想在不指定可選參數的情況下調用該函數,但仍然指定其余參數“ Z”

doTheThing('A', ...'Z');

預期產量:

'A', 'B', 'C', 'Z'

不幸的是,我得到以下信息:

Parsing error: Shorthand property assignments are valid only in destructuring patterns

我該如何解決呢?

JavaScript不允許提供命名參數或任何形式的參數跳過,因此無法使用當前形式的函數來執行所需的操作。 不過,這里有一些替代方法:

普通的JavaScript方法:將配置對象作為參數

而不是接受多個參數

func = (a, b, c) => { /* operate with parameters */ } 
func("One", "Two", "Three")

您的函數將改為接受一個對象

func = config => { /* operate with config */ }
func({a: "One", b: "Two", c: "Three"})

這是JavaScript中的一種常見模式,因為它允許您幾乎命名變量,並且不需要以正確的順序傳遞它們。它可以輕松傳遞大量變量,還可以使其易於默認他們也是。

 const doTheThing = (config) => { const defaultProperties = { b: "B", c: "C" } const {a, b, c, ...rest} = Object.assign({}, defaultProperties, config); const z = Object.values(rest); //extract their values, otherwise you get an object console.log(a, b, c, z); } doTheThing({a: "A", x: "X", y: "Y", z: "Z"}); 

與rest參數一起使用時有點笨拙,但並非不可行。

但是,這確實意味着,如果您有很多參數,則可能很難看清可以傳遞哪些參數以及需要哪些參數。

面向對象的方法:構建器模式

您將創建一個構建器對象-它用於保存值,直到調用final方法為止,此時將接受所有參數並一次性構造一個對象。

這就是更多面向對象語言處理大量參數的方式,您甚至可以選擇其中一些參數。 在JavaScript中看到這樣定義的構建器並不是很常見,但是也不太奇怪。 如果您已經使用類,甚至使用TypeScript,則可能更合適。

 class DoTheThingBuilder { constructor() { this.a = null; this.b = "B"; this.c = "C"; this.z = null; } withA(a) { this.a = a; return this; } withB(b) { this.b = b; return this; } withC(c) { this.c = c; return this; } withEverythingElse(...z) { this.z = z; return this; } doTheActualThing() { const {a, b, c, z} = this; console.log(a, b, c, z); } } const builder = new DoTheThingBuilder(); builder .withA("A") .withEverythingElse("X", "Y", "Z") .doTheActualThing(); 

如您所見,對於某些簡單任務,這可能非常冗長。 對於此示例來說,這是一個很大的矯kill過正,但是也許在實際使用中,您可能會發現它有所幫助。

我與通常的方法有所不同-通常,您將設置構建器所需的所有參數,最后調用構造一個對象的 .build() 在這種情況下,我基本上將build重命名為doTheActualThing並且它正在執行該功能。

功能方法:咖喱

currying的概念非常簡單-而不是擁有一個接受多個參數的函數

func = (a, b, c) => { /* operate with parameters */ }

您有一個帶有一個參數的函數,該函數返回一個帶有第二個參數的函數,返回另一個函數,依此類推,直到滿足所有參數為止,然后執行完整的函數。

func = a => b => c => { /* operate with parameters */ }

在許多方面,這與OO Builder模式等效。

 const doTheThing = (a) => (b = "B") => (c = 'C') => (...z) => console.log(a, b, c, z); doTheThing("A")()()("X", "Y", "Z"); 

這樣,您可以通過不提供第二個和第三個參數來跳過它們,從而獲得默認值。 它也比生成器短。 但是,閱讀該功能可能會有些奇怪。

這是不可能的,而且很容易出錯。 命名參數的關鍵是要知道它們是什么以及它們以什么順序出現。

使用object作為函數參數,您可以實現類似的效果:

const doTheThing = ({ a, b = "B", c = "C", others = {} }) => {
  const params = { a, b, c, ...others }; // this will merge your parameters into one object
  console.log(params);
}

doTheThing({ a: "A", others: { z: "Z" }});

這將記錄A,B,C,Z。演示: https//codepen.io/tomekbuszewski/pen/jQqmNL? editors = 0011

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM