Node.js中matchAll返回Object [RegExp String Iterator] {}是什么含义
matchAll打印仅显示迭代器标识的原因及解决方案
核心原因
String.prototype.matchAll()的返回值本身就是RegExp String Iterator类型的迭代器对象,而非直接存储匹配结果的数组。Node.js的console.log打印迭代器时,默认只会输出其类型标记,不会自动遍历展开内部存储的匹配结果,因此你只会看到Object [RegExp String Iterator] {}的输出。
常见处理方案
- 使用扩展运算符将迭代器转换为数组后打印:
const res = 'test string 123 test 456'.matchAll(/test/g) console.log([...res]) - 使用
Array.from方法将迭代器转换为数组:const res = 'test string 123 test 456'.matchAll(/test/g) console.log(Array.from(res)) - 使用
for...of循环直接遍历迭代器,逐个处理匹配结果:for (const matchItem of 'test string 123 test 456'.matchAll(/test/g)) { console.log(matchItem) }
注意:使用
matchAll方法时,传入的正则表达式必须带有g全局修饰符,否则会抛出TypeError异常。
内容的提问来源于stack exchange,提问作者Samuel Ramos
相关产品推荐
相关产品推荐

