for循环通过带有对象的数组

时间:2017-11-08 23:21:06

标签: javascript jquery

我试图循环一个包含各种对象的数组,这是我的代码 - 任何提示?

 var companies = [
                 {name: 'dhillion', imgCount: 1},
                 {name: 'blinds', imgCount: 2},
                 {name: 'honda', imgCount: 2},
                 {name: 'nike', imgCount: 3},
                 {name: 'protilla', imgCount: 3},
                 {name: 'starbucks', imgCount: 4}
                ];

// for(var i =0; i < companies.length; i++){
//     console.log(companies.name + '..' + companies.imgCount);
// }

for(var k in companies){
    console.log(companies.name[k] + '..' + companies.imgCount[k]);
}

2 个答案:

答案 0 :(得分:-1)

你很接近,你错过了引用数组中的位置。

     var companies = [
                 {name: 'dhillion', imgCount: 1},
                 {name: 'blinds', imgCount: 2},
                 {name: 'honda', imgCount: 2},
                 {name: 'nike', imgCount: 3},
                 {name: 'protilla', imgCount: 3},
                 {name: 'starbucks', imgCount: 4}
                ];

for(var i =0; i < companies.length; i++){
    console.log(companies[i].name + '..' + companies[i].imgCount);
}

https://jsfiddle.net/brm0kx2d/

上面的工作示例

答案 1 :(得分:-1)

我个人会使用for each逻辑让javascript为你处理索引。

&#13;
&#13;
var companies = [{
    name: 'dhillion',
    imgCount: 1
  },
  {
    name: 'blinds',
    imgCount: 2
  },
  {
    name: 'honda',
    imgCount: 2
  },
  {
    name: 'nike',
    imgCount: 3
  },
  {
    name: 'protilla',
    imgCount: 3
  },
  {
    name: 'starbucks',
    imgCount: 4
  }
];

if (Array.prototype.forEach) {
  //native logic if the browser supports it
  companies.forEach(function(company){
    console.log(company.name);
  });
} else {
  //jQuery logic fallback if it does not, or you could just do this and not worry about testing for the fallback
  $.each(companies, function(index, company){
    console.log(company.name);
  });
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;