freecodecamp.cn icon indicating copy to clipboard operation
freecodecamp.cn copied to clipboard

检查对象是否有某属性为什么要用hasOwnProperty

Open pyhui opened this issue 10 years ago • 3 comments

Challenge Testing Objects for Properties

My code:

// 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");

////// 该程序中 if(myObj.hasOwnProperty(checkProp))可以直接写成 if(myObj[checkProp]) 所以检查对象是否有某属性为什么还要用hasOwnProperty呢?

pyhui avatar Oct 27 '16 17:10 pyhui

Stop...STOP... STOP...WRITING ME... STOP...STOP...STOP...WRITING ME...STOP.. STOP...STOP...WRITING!!!!!!!

jamesbeme avatar Oct 27 '16 21:10 jamesbeme

当myObj[checkProp]为0或者空时,你就没法用这种方式判断了

discountry avatar Oct 30 '16 05:10 discountry

@pyhui 尽管在这题用myObj[checkProp]也能通过测试。 但代码并不严谨,所以还是推荐:myObj.hasOwnProperty(checkProp)

huluoyang avatar Nov 01 '16 09:11 huluoyang