TypeError:this.list.push不是ecmascript 6中的函数

TypeError: this.list.push is not a function in ecmascript 6

本文关键字:函数 ecmascript 不是 this list push TypeError      更新时间:2023-09-26

当调用GroceryList类的add函数时,我得到一个错误:

类型错误:this.list.push不是函数

为什么会这样?

class GroceryList {
      constructor() {
        this.list = {
            value: [],
            writable: false,
            enumerable: true  
          };
      }
        add(item) {
        this.list.push(item);
      }
      getAll() {
        return this.list;
      }
      getItemIndex(value) {
        var index = this.list.length;
        while(--index > -1) {
          if(this.list[index] === value) {
            return index;
          }
        }
        return -1;
      }
    }

您混淆了

  • 整个对象

  • 作为该对象属性的列表

list对象包含一个列表,但这并不意味着它是一个列表。您应该编写list.value.push(x)

您似乎正在尝试使用属性描述符。然而,这些描述符仅适用于Object.defineProperty

this.list = {
  value: [],
  writable: false,
  enumerable: true  
};

从字面上将具有属性valuewritableenumerable的对象分配给this.list

你似乎想要的是:

Object.definProperty(this, 'list', {
  value: [],
  writable: false,
  enumerable: true  
});

现在this.list返回一个数组,但不可能为该属性分配新值。