简体   繁体   English

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

[英]Why my javascript code doesnt show "Not Found"?

it doesnt show Not Found , it shows undefined它不显示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"))

You are using hasOwnProperty wrong:您正在使用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 is a method and it takes a parameter. hasOwnProperty是一个方法,它需要一个参数。 You have to call it like this hasOwnProperty(checkprob) .你必须这样称呼它hasOwnProperty(checkprob) See also the documentation .另请参阅文档

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

Missing function call.缺少函数调用。 You can also use in operator.您也可以使用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"
      )
    );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM