如何在vue.js2上循环对象观察器?

如果我console.log(this.list),结果如下:

this.list.forEach(function (user) {
    selected.push(user.id);
});

存在错误:

未捕获的TypeError:this.list.forEach不是函数

如何解决此错误?


解决方案

this.list不是数组吗?

如果this.list类似于数组(该对象上必须有length属性),您应该能够执行以下操作:

Array.prototype.forEach.call(this.list, user => {
  // ...
})

Array.from(this.list).forEach(user => {
  // ...
})

[...this.list].forEach(user => {
  // ...
})

否则,如果this.list只是一个普通对象,您可以这样做:

Object.keys(this.list).forEach(key => {
  const user = this.list[key]
  // ...
})

Object.entries(this.list).forEach(([key, user]) => {
  // ...
})

相关文章