如何在使用for ... in循环

时间:2018-05-20 00:36:13

标签: javascript for-in-loop

const dog = {
   id:1,
   name : "Henry",
   breed: "border-collie"
}

   for(let prop in dog){
      if(prop.name === id && typeof prop === "number"){
          console.log("this prop is ok!")
          continue
      }
      if(prop.name === name && prop === "Henry"){
          console.log("prop is ok!")
          continue
      }
      if(prop.name === breed && prop === "border-collie"){
          console.log("mucho bueno")
          continue
      }
      else{
        console.warn("prop could not be identified") 
        break
      }
   }

所以我在这里有一些代码是正确的,我相信,除了.name伪属性。我想循环查看狗的所有属性列表,但我也希望能够检查每个狗的属性名称,以确保它们有效。

有没有办法在for ... in循环中执行此操作。如果没有,我还能做些什么才能循环通过道具并检查道具名称?

2 个答案:

答案 0 :(得分:0)

MongoLocations.find({'_id': { $in: org.locations } }, function (err, locations) {
   if (err) res.send(err);
   res.json(locations);
})

这会迭代键(id,name,breed)。

相应的值将是dog [key]。

答案 1 :(得分:0)

prop已经是属性名称,作为字符串;值为dog[prop]

const dog = {
    id: 1,
    name: "Henry",
    breed: "border-collie"
}

for (let prop in dog) {
    if (prop === "id" && typeof dog[prop] === "number") {
        console.log("this prop is ok!")
        continue
    }
    if (prop === "name" && dog[prop] === "Henry") {
        console.log("prop is ok!")
        continue
    }
    if (prop === "breed" && dog[prop] === "border-collie") {
        console.log("mucho bueno")
        continue
    } else {
        console.warn("prop could not be identified") 
        break
    }
}

您还可以使用Object.entries按键迭代键和值:

for (let [name, value] of Object.entries(dog)) {
    if (name === "id" && typeof value === "number") {
        console.log("this prop is ok!")
    } else if (name === "name" && value === "Henry") {
        console.log("prop is ok!")
    } else if (name === "breed" && value === "border-collie") {
        console.log("mucho bueno")
    } else {
        console.warn("prop could not be identified") 
        break
    }
}