gpt4 book ai didi

javascript - 遍历数组中的数组以确定值

转载 作者:行者123 更新时间:2023-11-29 20:46:23 26 4
gpt4 key购买 nike

我需要使用 for 循环遍历以下数组,并确定这些人的年龄是 18 岁及以上,还是未满 18 岁并相应地记录一个字符串。

我一直在尝试这样一些不同的事情:

var peopleWhoWantToSeeMadMaxFuryRoad = [
{
name: "Mike",
age: 12,
gender: "male"
},{
name: "Madeline",
age: 80,
gender: "female"
},{
name: "Cheryl",
age: 22,
gender: "female"
},{
name: "Sam",
age: 30,
gender: "male"
},{
name: "Suzy",
age: 4,
gender: "female"
}
]


for(var i = 0; i < peopleWhoWantToSeeMadMaxFuryRoad.length; i++){
for(var j = 0; j < peopleWhoWantToSeeMadMaxFuryRoad[i].length; j++){
if (j == 'number' && j < 18){
console.log("person is under 18")
}
}
}

但我似乎无法理解。任何帮助将不胜感激

最佳答案

不需要双for循环,你可以用一个for循环来实现:

for(var i = 0; i < peopleWhoWantToSeeMadMaxFuryRoad.length; i++){
if(peopleWhoWantToSeeMadMaxFuryRoad[i].age < 18) {
// Do something for underaged people;
} else {
// Do something for people over 18
}
}

或者您可以使用 foreach 循环:

peopleWhoWantToSeeMadMaxFuryRoad.forEach(function(person) {
if(person.age < 18) {
// Do something for underaged people;
} else {
// Do something for people over 18
}
});

关于javascript - 遍历数组中的数组以确定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392201/

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