* fix: convert js algorithms and data structures * fix: revert some blocks back to blockquote * fix: reverted comparison code block to blockquotes * fix: change js to json Co-Authored-By: Oliver Eyton-Williams <ojeytonwilliams@gmail.com> * fix: convert various section to triple backticks * fix: Make the formatting consistent for comparisons
2.4 KiB
2.4 KiB
id, title, challengeType
| id | title | challengeType |
|---|---|---|
| 587d7dae367417b2b2512b7b | Understand Own Properties | 1 |
Description
Bird constructor defines two properties: name and numLegs:
function Bird(name) {
this.name = name;
this.numLegs = 2;
}
let duck = new Bird("Donald");
let canary = new Bird("Tweety");
name and numLegs are called own properties, because they are defined directly on the instance object. That means that duck and canary each has its own separate copy of these properties.
In fact every instance of Bird will have its own copy of these properties.
The following code adds all of the own properties of duck to the array ownProps:
let ownProps = [];
for (let property in duck) {
if(duck.hasOwnProperty(property)) {
ownProps.push(property);
}
}
console.log(ownProps); // prints [ "name", "numLegs" ]
Instructions
own properties of canary to the array 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);