freeCodeCamp/curriculum/challenges/chinese/02-javascript-algorithms-an.../object-oriented-programming/understand-own-properties.md

2.1 KiB
Raw Blame History

id title challengeType forumTopicId dashedName
587d7dae367417b2b2512b7b 了解自有属性 1 301326 understand-own-properties

--description--

请看下面的实例,Bird 构造函数定义了两个属性:namenumLegs

function Bird(name) {
  this.name  = name;
  this.numLegs = 2;
}

let duck = new Bird("Donald");
let canary = new Bird("Tweety");

namenumLegs 被叫做 own 属性,因为他们是直接在实例对象上定义的。 这就意味着 duckcanary 这两个对象分别拥有这些属性的独立副本。 事实上,Bird 的所有实例都将拥有这些属性的独立副本。 以下的代码将 duck 里面所有的 own 属性都存到一个叫 ownProps 的数组里面:

let ownProps = [];

for (let property in duck) {
  if(duck.hasOwnProperty(property)) {
    ownProps.push(property);
  }
}

console.log(ownProps);

控制台将显示值 ["name", "numLegs"]

--instructions--

canary 对象里面的 own 属性添加到 ownProps 数组里面。

--hints--

ownProps 应该包含 numLegsname 两个属性的值。

assert(ownProps.indexOf('name') !== -1 && ownProps.indexOf('numLegs') !== -1);

在不使用内置方法 Object.keys() 的前提下完成这个挑战。

assert(!/Object(\.keys|\[(['"`])keys\2\])/.test(code));

你应该解决这个挑战,而不是硬编码 ownProps 数组。

assert(
  !/\[\s*(?:'|")(?:name|numLegs)|(?:push|concat)\(\s*(?:'|")(?:name|numLegs)/.test(
    code
  )
);

--seed--

--seed-contents--

function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let canary = new Bird("Tweety");
let ownProps = [];
// Only change code below this line

--solutions--

function Bird(name) {
  this.name = name;
  this.numLegs = 2;
}

let canary = new Bird("Tweety");
function getOwnProps (obj) {
  const props = [];

  for (let prop in obj) {
    if (obj.hasOwnProperty(prop)) {
      props.push(prop);
    }
  }

  return props;
}

const ownProps = getOwnProps(canary);