具有JavaScript过滤器功能的堆栈溢出

问题描述 投票:0回答:1

大家好,我试图用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());

也许我只是累了,但我看不到过滤器功能如何导致堆栈溢出!

javascript stack-overflow
1个回答
1
投票

正确方法

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());
© www.soinside.com 2019 - 2024. All rights reserved.