?print-pdf' Created by
for...in statementfor...in statementfor...of statement, which is mainly used to loop over arrays.
let obj = {a:1, b:2};
for(const key in obj){
console.log(`${key} - ${obj[key]}`);
}
for...in iterates over inherited properties
const Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
console.log(`Hello, I.m ${this.name} and I'm ${this.age} years old`);
}
let pesho = new Person('Pesho', 23);
// pesho.greet();
for(const key in pesho){
console.log(`${key} - ${pesho[key]}`);
}
// name - Pesho
// age - 23
// greet - function
for...in to iterate over own properties only
const Person = function (name, age) {
this.name = name;
this.age = age;
}
Person.prototype.greet = function () {
console.log(`Hello, I.m ${this.name} and I'm ${this.age} years old`);
}
let pesho = new Person('Pesho', 23);
// pesho.greet();
for(const key in pesho){
if(pesho.hasOwnProperty(key)){
console.log(`${key} - ${pesho[key]}`);
}
}
// name - Pesho
// age - 23
for...in with for...of
let obj = {a:1, b:2};
for(const key of obj){
console.log(`key: ${key}`);
}
// TypeError: obj is not iterable
Object.keys, Object.values, Object.entriesObject.keys, Object.values, Object.entriesObject.keys(obj) - return an array of obj properties namesObject.value(obj) - return an array of obj properties valuesObject.entries(obj) - return an array of arrays. Each inner array has two item. The first item is the property name; the second item is the value.
let obj = { a:1, b:2 };
let keys = Object.keys(obj);
let values = Object.values(obj);
let entries = Object.entries(obj);
console.log("keys:", keys);
console.log("values:", values);
console.log("entries:", entries);
// keys: [ 'a', 'b' ]
// values: [ 1, 2 ]
// entries: [ [ 'a', 1 ], [ 'b', 2 ] ]
Object.keys - example
let obj = { a:1, b:2 };
// get the keys as array:
let keys = Object.keys(obj);
// loop through keys array:
for(const key of keys){
console.log(`${key} - ${obj[key]}`);
}
// a - 1
// b - 2
Object.entries - example
let obj = { a:1, b:2 };
let entries = Object.entries(obj);
for(const [key,value] of entries){
console.log(`${key} - ${value}`);
}
// a - 1
// b - 2
These slides are based on
customised version of
framework