我有以下代理:
const p = new Proxy({
[Symbol.iterator]: Array.prototype.values,
forEach: Array.prototype.forEach,
}, {
get(target, property) {
if (property === '0') return 'one';
if (property === '1') return 'two';
if (property === 'length') return 2;
return Reflect.get(target, property);
},
});
它是一个类似数组的对象,因为它具有数值属性和length
指定元素数量的属性。我可以使用循环对其进行迭代for...of
:
for (const element of p) {
console.log(element); // logs 'one' and 'two'
}
但是,该forEach()
方法不起作用。
p.forEach(element => console.log(element));
此代码不记录任何内容。永远不会调用回调函数。为什么它不起作用,我该如何解决?
代码片段:
const p = new Proxy({
[Symbol.iterator]: Array.prototype.values,
forEach: Array.prototype.forEach,
}, {
get(target, property) {
if (property === '0') return 'one';
if (property === '1') return 'two';
if (property === 'length') return 2;
return Reflect.get(target, property);
},
});
console.log('for...of loop:');
for (const element of p) {
console.log(element);
}
console.log('forEach():');
p.forEach(element => console.log(element));
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.16.0/polyfill.min.js"></script>