3 回答

TA贡献1797条经验 获得超6个赞
您使用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"));

TA贡献1836条经验 获得超5个赞
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"))

TA贡献1878条经验 获得超4个赞
缺少函数调用。您也可以使用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"
)
);
添加回答
举报