[已解决]基础 JavaScript - 测试对象的属性

告诉我们发生了什么:
题目要求 修改函数 checkObj 检查 obj 是否有 checkProp 属性。 如果属性存在,返回属性对应的值。 如果不存在,返回"Not Found"
我不知道该怎么返回属性对应的值,我分不清
return(checkObj);
return(obj);
return(checkProp);
以及正确答案中的
return obj[checkProp];
这些返回的都是什么?

你目前的代码

function checkObj(obj, checkProp) {
 if (checkObj.hasOwnProperty("checkProp")){
   **return(checkObj);**
 }
  else {
    return "Not Found";
    }
}

请提供题目的网址, 让别人去理解题目的要求

Yes, you should always provide a link to the challenge.

This:

return(checkObj);

is normally written as:

return checkObj;

But checkObj is jus the function. You want to check if the object passed (obj) has a property of the string help in the variable checkProp. You are checking if the function checkObj has a property called “checkProp” - not what is held in that variable but that specific name.

So, you need to change this line:

if (checkObj.hasOwnProperty("checkProp")){

so that you are checking the correct object and using the variable checkProp, not a string with that value.

And then here:

return checkObj;

you need to return the value in the object passed (not the function) with the property contained in checkProp. Do you know how to use a variable to get an object value?

抱歉 这里是题目的网址

就是让你写一个检查一个对象是否存在指定的属性,如果存在就返回该对象中属性的属性值,反之就返回“Not Found”这么一个函数。

/*首先函数体是已经准备好的,只需要写逻辑就行了*/
function checkObj(obj, checkProp) {
//只修改这一行下面的代码
//使用对象的hasOwnProperty方法判断obj对象中是否存在checkProp这个属性
  if(obj.hasOwnProperty(checkProp)){
    //存在就返回该对象中属性的属性值
    return obj[checkProp]
  }
  else {
    //不存在就返回Not Found
    return "Not Found"
  }
//只修改这一行上面的代码
}

//演示
//初始化一个对象,以及需要查找的属性,调用函数checkObj
const obj = {name: "哈哈"}
let prop = "name"
let props = "age"
console.log(checkObj(obj,prop)) //返回"哈哈"
console.log(checkObj(obj,props)) //返回"Not Found"