为什么我的 javascript 代码不显示“未找到”?

它不显示Not Found,它显示undefined


function checkObj(obj, checkprob) {

  if (obj.hasOwnProperty) {

    return obj[checkprob];

  } else {

    return "Not Found"

  }

}


console.log(checkObj({

  gift: "pony",

  pet: "kitten",

  bed: "sleigh"

}, "Amir"))


HUWWW
浏览 175回答 3
3回答

互换的青春

您使用hasOwnProperty错误:function checkObj(obj, checkprob){     if(obj.hasOwnProperty(checkprob)){          return obj[checkprob];     } else{          return "Not Found";     } }console.log(checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "Amir"));console.log(checkObj({gift: "pony", pet: "kitten", bed: "sleigh"}, "bed"));

一只甜甜圈

hasOwnProperty是一种方法,它需要一个参数。你必须这样称呼它hasOwnProperty(checkprob)。另请参阅文档。function checkObj(obj, checkprob) {  if (obj.hasOwnProperty(checkprob)) {    return obj[checkprob];  } else {    return "Not Found"  }}console.log(checkObj({  gift: "pony",  pet: "kitten",  bed: "sleigh"}, "Amir"))

UYOU

缺少函数调用。您也可以使用in运算符。function checkObj(obj, checkprob){     if(obj.hasOwnProperty(checkprob)){          return obj[checkprob];     } else{          return "Not Found";     } }    function checkObj2(obj, checkprob) {      if (checkprob in obj) {        return obj[checkprob];      } else {        return "Not Found";      }    }    console.log(      checkObj2(        {          gift: "pony",          pet: "kitten",          bed: "sleigh"        },        "Amir"      )    );
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript