zilongxuan001 / LearnFreecode

0 stars 0 forks source link

Testing Objects for Properties #256

Open zilongxuan001 opened 6 years ago

zilongxuan001 commented 6 years ago

介绍

254 删除属性

253 增加属性

252 修改属性

有时你得去查找一个属性是否真的存在。

这就用object.hasOwnProperty(propname)方法来确定对象的有没有某个属性,有则返回true,无则返回false

方法

var myObj = {
   "top": "hat",
   "bottom": "pants"
};

myObj.hasOwnProperty("top");   //true
myObj.hasOwnProperty("middle"); //false

练习

Modify the function checkObj to test myObj for checkProp. If the property is found, return that property's value. If not, return "Not Found".

代码


// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here
  if(myObj.hasOwnProperty(checkProp)){
    return myObj[checkProp];
  } else{
    return "Not Found";
  }  

}

// Test your code by modifying these values
checkObj("gift");

结果显示

image

来源

https://www.freecodecamp.org/challenges/testing-objects-for-properties