[英]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.