我目前正在尝试用好奇的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++;
}
}
答案 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'));