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

成功男人

如果我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]) => {
  // ...
})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章