迭代语法问题ForEach Vue.js

时间:2018-12-06 09:27:57

标签: javascript vue.js foreach iteration

我尝试使用Vue.js进行迭代 结果出现了这样的错误

[Vue警告]:挂接钩中出现错误:“ TypeError:this.frontImages.forEach不是函数”

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 


this.frontImages.forEach(function(value, index) {

  console.log(value);

}

2 个答案:

答案 0 :(得分:1)

.forEach()仅适用于数组。

如果您需要遍历JSON对象的属性,那么这是一种实现方法:

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 

var arr = Object.keys(this.frontImages);

arr.forEach(function(value, index) {

  console.log(value, this.frontImages[value]);

});

答案 1 :(得分:-1)

对于数组:

this.frontImages = [{frontA:{name:'frontAName'},frontB:{name:'frontBName'}}]; 

this.frontImages.forEach(function(value, index) {

  console.log(value);

})

仅用于对象迭代

this.frontImages = {frontA:{name:'frontAName'},frontB:{name:'frontBName'}}; 

Object.values(this.frontImages).forEach(value => {

  console.log(value);

});