[英]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.