[英]Is there a way to map array items to function parameters in typescript directly?
I often end up with a situation where i got an array with arguments and have to manually break the array into parts. 我经常最终得到一个带有参数的数组并且必须手动将数组分成几部分的情况。 For example
例如
Observable.combineLatest(obs1$, obs2$, obs3$).subscribe((data) => {
let fancyArg = data[0];
let epicArg = data[1];
let wonderfulArg = data[2];
})
Is there a shortcut to do something like this 有没有做这样的事情的捷径
Observable.combineLatest(obs1$, obs2$, obs3$)
.subscribe([fancyArg, epicArg, wonderfulArg] => { //something like this
... //would be great
})
I know that there is the option with the last argument as function 我知道最后一个参数的选项是函数
Observable.combineLatest(obs1$, obs2$, obs3$,
(arg1, arg2, arg3) => {
return {
fancyArg:arg1,
epicArg:arg2,
wonderfulArg:arg3
}
})
.subscribe((args) => {
...
})
but this is also very unhandy. 但这也很不方便。 I look for a more general approach (to use it by bindCallback and other functions as well)
我寻找更通用的方法(通过bindCallback和其他函数使用它)
Javascript has destructuring assignment which you can use in your parameter list to unpack an array. Javascript具有解构赋值 ,您可以在参数列表中使用它来解压缩数组。 Example:
例:
function takeAnArray([firstItem, secondItem, thirdItem]) { console.log(firstItem, secondItem, thirdItem); } takeAnArray([1, "a", false]);
So you were almost right in your second snippet. 所以你几乎在你的第二个片段中。 You just need to add a pair of parenthases around the argument list:
您只需要在参数列表周围添加一对父级:
Observable.combineLatest(obs1$, obs2$, obs3$)
.subscribe(([fancyArg, epicArg, wonderfulArg]) => {
// Here, fancyArg is the first array element,
// epicArg is the second
// wonderfulArg is the third
})
The documentation for combineLatest
even shows this syntax in it's first example. combineLatest
的文档甚至在它的第一个示例中显示了这种语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.