ES6 RegExps 会支持 Iterator 协议吗?

Will ES6 RegExps support the Iterator protocol?

我无法在 the spec or list of proposals as to whether RegExps in ES6 will provide the necessary methods to support the Iterator protocol 中找到匹配组的答案。有很多符号方法,但我对各种符号的语义还不够熟悉,不知道它们是否会提供这个。

我会想象这样的事情:

var rex = /((\w+)\s?)*/;
var res = rex.exec("test string");

console.log(res);

for (let match of res) {
    console.log(match);
}

这似乎在 6to5 的 REPL 中有效,记录了预期的 "test string""string""string".

这是在 ES6 规范中明确定义的吗?如果没有,正则表达式结果的哪些属性允许它工作?或者它只是 6to5 的产物而不是 ES6?

res 只是 Array 的匹配项。您可以使用以下变体之一来检查它:

Object.prototype.toString.call(res) === '[object Array]'
res instanceof Array;
Array.isArray(res);
res.constructor === Array;

而且 ES6 中的数组支持迭代器接口。参见 here, or in MDN: Array.prototype[@@iterator]

关于 inputindex 属性 - 它们只是通过 exec 方法添加到 res 数组中。例如,您可以查看 v8 源代码: