【问题标题】:Iteration Syntax issue ForEach Vue.jsForEach Vue.js 的迭代语法问题
【发布时间】:2019-05-07 23:03:22
【问题描述】:

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

[Vue 警告]:挂载钩子错误:“TypeError: this.frontImages.forEach 不是函数”

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


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

  console.log(value);

}

【问题讨论】:

  • .forEach() 仅适用于数组。它不适用于 JSON 对象。
  • 我们如何迭代这个对象

标签: javascript vue.js foreach iteration


【解决方案1】:

.forEach() 仅适用于数组。

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

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

printKeysAndValues(this.frontImages);

function printKeysAndValues(anyObject) {
    Object.keys(anyObject).forEach( key => {

        // in-case properties are nested objects
        let value = JSON.stringify(anyObject[key]);  

        
        // let value = anyObject[key];   // for primitive nested properties


        console.log(`${key} = ${value}`);
    });
}

【讨论】:

    【解决方案2】:

    对于数组:

    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);
    
    });

    【讨论】:

    • OP想要遍历JSON对象,而不是把JSON变成一个数组。
    猜你喜欢
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多