如何使用vanilla javascript循环遍历数组内的对象

时间:2018-03-22 18:45:56

标签: javascript

var people = [  
  {
    name: "Mike",
    age: 12,
    gender: "male"
  },{
    name: "Madeline",
    age: 80,
    gender: "female"
  }
]

如何循环播放数组并登录到控制台"足够老"如果他们年满18周岁,而且年龄不够大"如果你不是18岁。我该怎么做,任何帮助,提前谢谢

7 个答案:

答案 0 :(得分:1)

  for(const person of people)
    console.log(`is ${person.age < 18 ? "not" : ""} old enough`);

答案 1 :(得分:0)

//Iterate your objects, check their age property to see if greater than equal to 18
for(let x = 0; x < people.length; x++) {
     if(people[x].age >= 18){
        console.log(people[x].name + " Is Old Enough");
     }else {
        console.log(people[x].name + " Is Not Old Enough");
     } 
}

答案 2 :(得分:0)

people.forEach((node)=>{
    if(node.age > 18) {
    console.log("old enough")
  }else {
    console.log("not old enough")
  }
})

答案 3 :(得分:0)

您可以使用forEach方法。

 people.forEach((element)=>{
     element.age >= 18 ? console.log('Old Enough') : console.log('Not old enough')
 });

答案 4 :(得分:0)

&#13;
&#13;
var people = [{
  name: "Mike",
  age: 12,
  gender: "male"
}, {
  name: "Madeline",
  age: 80,
  gender: "female"
}]

for (var i = 0; i < people.count; i++) {
  if (people[i].age < 18) {
    console.log("too young message");
  } else {
    console.log("old enough message");
  }
}
&#13;
&#13;
&#13;

答案 5 :(得分:0)

&#13;
&#13;
var people = [
{ name: "Mike", age: 12, gender: "male" },{ name: "Madeline", age: 80, gender: "female" } ];

people.forEach(person=>{
  console.log(person.age >= 18 ? "Old enough": "Not old enough");
  return;
});
&#13;
&#13;
&#13;

答案 6 :(得分:0)

people.map(
  item => {
     console.log(
       (item.age>18)?item.name+' is old enough':item.name+' is not old enough'
     )
   }
 )