gpt4 book ai didi

javascript - 将 for in 替换为带有对象的常规 for 循环

转载 作者:行者123 更新时间:2023-11-28 12:20:05 24 4
gpt4 key购买 nike

出于好奇,我目前正在尝试用常规 for 循环替换我的 for in 循环,但没有成功。我总是得到未定义。这对于 javascript 对象来说是可能的吗?

我循环的示例对象:

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 循环方法总是让我无法读取未定义的属性“类型”:

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

最佳答案

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

关于javascript - 将 for in 替换为带有对象的常规 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333192/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com