Challenge: Object Property Iteration with hasOwnProperty()
Task
Create a loop that iterates through the properties of an object and prints each property along with its value. However, you should only print properties that belong directly to the object, not those inherited from its prototype chain. Utilize the hasOwnProperty()
method to achieve this.
99
1
2
3
4
5
6
7
8
9
10
11
12
const song = {
name: "Bohemian Rhapsody",
band: "Queen",
released: "31 October 1975",
duration: 355,
};
___ (___ ___ in ___) {
if (song.___(key)) {
console.log(`${key}:`, song[key]);
}
}
123456789101112const song = { name: "Bohemian Rhapsody", band: "Queen", released: "31 October 1975", duration: 355, }; ___ (___ ___ in ___) { if (song.___(key)) { console.log(`${key}:`, song[key]); } }
Expected output:
python91234name: Bohemian Rhapsodyband: Queenreleased: 31 October 1975duration: 355
Use a
for...in
loop to iterate through the object's properties.Within the loop, check if each property is an own property of the object using
hasOwnProperty()
before logging it.
99
1
2
3
4
5
6
7
8
9
10
11
12
const song = {
name: "Bohemian Rhapsody",
band: "Queen",
released: "31 October 1975",
duration: 355,
};
for (let key in song) {
if (song.hasOwnProperty(key)) {
console.log(`${key}:`, song[key]);
}
}
123456789101112const song = { name: "Bohemian Rhapsody", band: "Queen", released: "31 October 1975", duration: 355, }; for (let key in song) { if (song.hasOwnProperty(key)) { console.log(`${key}:`, song[key]); } }
Tutto è chiaro?
Grazie per i tuoi commenti!
Sezione 3. Capitolo 4
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione