2.9 KiB
Raw Blame History

id, title, challengeType, forumTopicId, localeTitle
id title challengeType forumTopicId localeTitle
587d7dae367417b2b2512b7b Understand Own Properties 1 301326 Понять собственные свойства

Description

В следующем примере конструктор Bird определяет два свойства: name и numLegs :
функция Bird (name) {
this.name = name;
this.numLegs = 2;
}

пусть утка = новая птица («Дональд»);
let canary = new Bird («Tweety»);
name и numLegs называются own свойствами, поскольку они определяются непосредственно на объекте экземпляра. Это означает, что duck и canary имеют свою отдельную копию этих свойств. Фактически каждый экземпляр Bird будет иметь свою собственную копию этих свойств. Следующий код добавляет все own свойства duck к массиву ownProps :
let ownProps = [];

для (пусть свойство в утке) {
if (duck.hasOwnProperty (свойство)) {
ownProps.push (свойство);
}
}

console.log (ownProps); // печатает ["name", "numLegs"]

Instructions

Добавьте own свойства canary к массиву ownProps .

Tests

tests:
  - text: <code>ownProps</code> should include the values <code>"numLegs"</code> and <code>"name"</code>.
    testString: assert(ownProps.indexOf('name') !== -1 && ownProps.indexOf('numLegs') !== -1);
  - text: Solve this challenge without using the built in method <code>Object.keys()</code>.
    testString: assert(!/Object(\.keys|\[(['"`])keys\2\])/.test(code));
  - text: Solve this challenge without hardcoding the <code>ownProps</code> array.
    testString: assert(!/\[\s*(?:'|")(?:name|numLegs)|(?:push|concat)\(\s*(?:'|")(?:name|numLegs)/.test(code));

Challenge Seed

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

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

Solution

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);