簡體   English   中英

有沒有辦法直接將數組項映射到typescript中的函數參數?

[英]Is there a way to map array items to function parameters in typescript directly?

我經常最終得到一個帶有參數的數組並且必須手動將數組分成幾部分的情況。 例如

Observable.combineLatest(obs1$, obs2$, obs3$).subscribe((data) => {
  let fancyArg = data[0];
  let epicArg = data[1];
  let wonderfulArg = data[2];
})

有沒有做這樣的事情的捷徑

Observable.combineLatest(obs1$, obs2$, obs3$)
  .subscribe([fancyArg, epicArg, wonderfulArg] => { //something like this
    ...                                             //would be great
  })

我知道最后一個參數的選項是函數

Observable.combineLatest(obs1$, obs2$, obs3$, 
  (arg1, arg2, arg3) => {
    return {
      fancyArg:arg1, 
      epicArg:arg2, 
      wonderfulArg:arg3
    }
  })
  .subscribe((args) => {
    ...
  })

但這也很不方便。 我尋找更通用的方法(通過bindCallback和其他函數使用它)

Javascript具有解構賦值 ,您可以在參數列表中使用它來解壓縮數組。 例:

 function takeAnArray([firstItem, secondItem, thirdItem]) { console.log(firstItem, secondItem, thirdItem); } takeAnArray([1, "a", false]); 

所以你幾乎在你的第二個片段中。 您只需要在參數列表周圍添加一對父級:

Observable.combineLatest(obs1$, obs2$, obs3$)
  .subscribe(([fancyArg, epicArg, wonderfulArg]) => {
    // Here, fancyArg is the first array element,
    // epicArg is the second
    // wonderfulArg is the third
  })

combineLatest文檔甚至在它的第一個示例中顯示了這種語法。

暫無
暫無

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

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