如何在箭头函数中解构String.matchAll返回的混合数组对象?
如何在箭头函数中解构String.matchAll返回的混合数组
String.matchAll会返回带有index、input和groups属性的混合数组。
示例:
[...'abc'.matchAll(/a|b|c/g)]
返回结果:
0: ['a', index: 0, input: 'abc', groups: undefined] 1: ['b', index: 1, input: 'abc', groups: undefined] 2: ['c', index: 2, input: 'abc', groups: undefined] length: 3 [[Prototype]]: Array(0)
问题
能否在Array.map或Array.filter的箭头函数中解构matchAll的结果?更通用的问题是:当同时需要数组元素和属性时,如何在箭头函数中解构这类“混合数组”?
可行的for-of循环解构
可以在for-of循环中直接解构matchAll的结果:
for (const {0: m, index, input} of 'abc'.matchAll(/a|b|c/g)) { console.log(m, index, input) }
输出:
a 0 abc b 1 abc c 2 abc
箭头函数中的错误写法
直接在.map函数中使用对象解构会抛出语法错误:
[...'abc'.matchAll(/a|b|c/g)].map({0: m, index, input} => m)
错误信息:
Uncaught SyntaxError: Malformed arrow function parameter list
正确的箭头函数解构方式
解构对象字面量时,需要将其放在括号中:
[...'abc'.matchAll(/a|b|c/g)].map( ( {0: m, index, input} ) => m)
更复杂的应用示例
[...'abc'.matchAll( /a|b|c/g )].map( ({0: m, index, input}) => `${ input.substring(0, index) }[${ m }]${ input.substring( index + m.length ) }`)
返回结果:
0: "[a]bc" 1: "a[b]c" 2: "ab[c]"
内容的提问来源于stack exchange,提问作者Kostya Hmelnitski
相关产品推荐
相关产品推荐

