更直接地查找可枚举属性



我有以下内容,它遍历对象/数组以打印其可枚举属性:

const reg = /(?<num>hi)(there)/g;
const str = 'hithere';
let matches = Array.from(str.matchAll(reg)); // same thing as [...matches[;]]
for (let match of matches) {
for (let elem of match) {
console.log('**', elem);
}
}

实际对象如下所示:

[
'hithere'.   // enumerable
'hi',        // enumerable
'there',     // enumerable
index: 0,                                      // no
input: 'hithere',                              // no
groups: [Object: null prototype] { num: 'hi' } // no
], ...

有没有更直接的方法可以(1(获得对象中的可枚举属性;或者(2(测试Object属性是否可枚举?我原以为以下会起作用,但它似乎总是为我打印true

matches[0].propertyIsEnumerable('index'));

这是一个非常好的问题。

对于。。。of不一定像for…那样在对象中的所有可枚举属性上循环。。。在中。Javascript对象可以定义自己的可迭代协议。

您从propertyIsNumerable获得的布尔值是正确的。

因此,要直接回答您的问题:(1( 是的:a代表。。。在回路中(2( 否:你的测试运行良好

const reg = /(?<num>hi)(there)/g;
const str = 'hithere';
let matches = Array.from(str.matchAll(reg)); // same thing as [...matches[;]]
for (let match in matches) {
for (let elem in matches[match]) {
console.log(elem, matches[match][elem]);
}
}

最新更新