使用常规for循环替换for

时间:2016-10-30 20:16:51

标签: javascript loops oop object for-loop

我目前正在尝试用好奇的for循环替换for循环,但没有成功。我总是得到undefined。这甚至可以用javascript对象吗?

示例对象I循环遍历:

var el = {
    1: {type: "fish", commonName: "clownfish", scientificName: "sdasd", gender: "m", price: 1.99},
    2: {type: "fish", commonName: "dragonfish", scientificName: "dada", gender: "f", price: 2.99}
};

我的工作方式:

for (var element in el) {
   if (el[element].type === type && el.hasOwnProperty(element)) {
       elementNum++;
   }
}

简单的for循环方法总是让我Cannot read property 'type' of undefined

for(var i = 0, x = Object.keys(el).length; i < x; i++) {
   if (el[i].type === type && el.hasOwnProperty(i)) {
      elementNum++;
   }
}

2 个答案:

答案 0 :(得分:6)

当您在整个对象中的第一个键为0时,您正在从1开始循环。

var el = {
  1: {
    type: "fish",
    commonName: "clownfish",
    scientificName: "sdasd",
    gender: "m",
    price: 1.99
  },
  2: {
    type: "fish",
    commonName: "dragonfish",
    scientificName: "dada",
    gender: "f",
    price: 2.99
  }
};

var keyLength = Object.keys(el).length;

// I've simplified the for loop
for (var i = 1; i <= keyLength; i++) {
  console.log(el[i].commonName);
}

答案 1 :(得分:0)

我建议直接遍历对象的键。

function getCount(type) {
    return Object.keys(el).reduce(function (r, k) {
        return r + +(el[k].type === type);
    }, 0);
}

var el = { 1: { type: "fish", commonName: "clownfish", scientificName: "sdasd", gender: "m", price: 1.99 }, 2: { type: "fish", commonName: "dragonfish", scientificName: "dada", gender: "f", price: 2.99 } };

console.log(getCount('fish'));