大家好,我试图用JavaScript模仿一个带有对象的数组。我以为用getter模仿length函数很容易,但是看起来我的filter函数导致了堆栈溢出。由于某种原因,我无法弄清楚出了什么问题。您能发现错误吗?
const o = {
0: 'hello',
1: 'there',
fakeLen: () => {
return Object.keys(this).length
},
get length() {
const keys = Object.keys(this);
const filtered = keys.filter(key => typeof this[key] != 'function');
console.log('filtered array ', filtered);
return filtered.length;
}
};
console.log('correct? ', o.length);
console.log('wrong? ', o.fakeLen());
也许我只是累了,但我看不到过滤器功能如何导致堆栈溢出!
正确方法
const o = {
0: 'hello',
1: 'there',
fakeLen: function() { // NOT ARROW FN
return Object.keys(this).length
}
};
// define getter
Object.defineProperty(o, 'length', {
get: function() {
const keys = Object.keys(this);
return keys.length
}
})
console.log('correct? ', o.length);
console.log('wrong? ', o.fakeLen());