大家好,我试图用 JavaScript 中的对象模拟数组。我认为用 getter 模拟长度函数会很容易,但看起来我的过滤函数导致堆栈溢出。出于某种原因,我不知道出了什么问题。你能发现错误吗?
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());
也许我只是累了,但我没有看到过滤器函数如何导致堆栈溢出!
最佳答案
当你在 this
上调用 Object.keys()
方法时,你将获得对象内的所有属性,所以 keys
看起来像:
["0", "1", "fakeLen", "length"]
然后,当您过滤每个键时,您在上述数组中的每个元素上使用括号表示法。因此,您将执行以下操作:
typeof this["length"] != 'function'
因为 length
是一个 getter(由于 get
),this["length"]
将导致你的 length
方法被再次调用,从而重复该过程,直到出现堆栈溢出。
const o = {
get length(){
this["length"];
}
};
o.length
您可以使您的 length
属性不可枚举(如 Medet Tleukabiluly 所示),这样当您对其调用 Object.keys()
时,它会获胜不会出现在您的 keys
列表中,或者,您可以在过滤之前简单地从您的 key 中删除 "length"
:
const o = {
0: 'hello',
1: 'there',
get length() {
const keys = Object.keys(this).filter(key => key !== "length");
const filtered = keys.filter(key => typeof this[key] != 'function');
return filtered.length;
}
};
console.log(o.length);
关于javascript - 堆栈溢出与 JavaScript 过滤功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58386545/