2020-10-06 23:10:08 +05:30

1.8 KiB

id, challengeType, videoUrl, forumTopicId, title
id challengeType videoUrl forumTopicId title
567af2437cbaa8c51670a16c 1 https://scrimba.com/c/cm8Q7Ua 18324 测试对象的属性

Description

有时检查一个对象属性是否存在是非常有用的,我们可以用.hasOwnProperty(propname)方法来检查对象是否有该属性。如果有返回true,反之返回false示例
var myObj = {
  top: "hat",
  bottom: "pants"
};
myObj.hasOwnProperty("top");    // true
myObj.hasOwnProperty("middle"); // false

Instructions

修改函数checkObj检查myObj是否有checkProp属性,如果属性存在,返回属性对应的值,如果不存在,返回"Not Found"

Tests

tests:
  - text: <code>checkObj("gift")</code>应该返回<code>"pony"</code>。
    testString: assert(checkObj("gift") === "pony");
  - text: <code>checkObj("pet")</code>应该返回<code>"kitten"</code>。
    testString: assert(checkObj("pet") === "kitten");
  - text: <code>checkObj("house")</code>应该返回<code>"Not Found"</code>。
    testString: assert(checkObj("house") === "Not Found");

Challenge Seed

// Setup
var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};

function checkObj(checkProp) {
  // Your Code Here

  return "Change Me!";
}

// Test your code by modifying these values
checkObj("gift");

Solution

var myObj = {
  gift: "pony",
  pet: "kitten",
  bed: "sleigh"
};
function checkObj(checkProp) {
  if(myObj.hasOwnProperty(checkProp)) {
    return myObj[checkProp];
  } else {
    return "Not Found";
  }
}