0

当使用正则表达式从带有 matchAll() 的字符串中提取匹配项时,使用扩展运算符扩展为 Array 对象的结果 Iterable Object 显示具有多个成员的嵌套数组。

const regexUpperCaseTo = /(?<=\x2d|\x5f)[a-zA-Z0-9]/g;
const testVar1 = [...str.matchAll(regexUpperCaseTo)]

当我们打印出 testVar1 时,它显示:

[
  [ 's', index: 4, input: 'the-stealth-warrior', groups: undefined ],
  [ 'w', index: 12, input: 'the-stealth-warrior', groups: undefined ]
]

同样,作为一个可迭代对象,我们可以使用 for/of 循环来迭代返回数组的每个元素。

[ 's', index: 4, input: 'the-stealth-warrior', groups: undefined ]
[ 'w', index: 12, input: 'the-stealth-warrior', groups: undefined ]

但是,一旦我们测试每个成员的长度,它就会返回 1。

console.log(testVar1.forEach(x => console.log(x.length)))

除此之外,当我们尝试访问每个数组的第 0 个成员之外的成员时,它会返回undefined

每个返回的成员似乎只包含第一个元素,这是怎么回事?

4

1 回答 1

0

这是正常的(与返回的迭代器无关matchAll)。每个匹配项 - 就像从.match()and返回的匹配项一样.exec()- 是一个数组对象,其中包含整个匹配项和捕获的组作为元素。

此外,该数组还有一些特殊属性,例如.index,.input和 (从 ES2018 开始) .groups。另请参阅Javascript 中正则表达式 match() 的返回位置?RegExp 匹配的内容

于 2020-10-14T22:11:40.157 回答