24
loading...
This website collects cookies to deliver better user experience
for/of
and for/in
loops. let numbers = [1, 2, 3, 4], sum = 0;
for(let el of numbers) {
sum += el;
}
sum // => 10
numbers
array. Different from the initialize expression of the for loop, here you can see that the variable el
is assigned with the the next element of the numbers
array, before each loop execution.let numbers = [1, 2, 3, 4], sum = 0;
for(let el of numbers) {
sum += el;
numbers.push(sum);
}
console.log(sum);
// => iteration can never reach the end of the element, and loops infinitely.
TypeError because o is not iterable
. for/of
loop using either of these methods, Object.keys()
, Object.values()
or Object.entries()
. These are iterable because they return an array of properties.//Object.keys returns an array of property names
let o = { x: 1, y: 2, z: 3 };
let keys = "";
for(let k of Object.keys(o)) {
keys += k;
}
keys // => "xyz"
//Object.values returns an array of property values.
let sum = 0;
for(let v of Object.values(o)) {
sum += v;
}
sum // => 6
//Object.entries returns an array of keys and values.
let pairs = "";
for(let [k, v] of Object.entries(o)) {
pairs += k + v;
}
pairs // => "x1y2z3"
let occurrence = {};
for(let char of "Panama") {
if (occurrence[char]) {
occurrence[char]++;
} else {
occurrence[char] = 1;
}
}
occurrence // => {p: 1, a: 3, n: 1, m: 1}
const msg = "❤️🐶";
console.log(msg.length); //outputs => 4
for(let item of msg){
console.log("wuff"); // logs "wuff" 3 times
}
let text = "oh no no no no no way!";
let wordSet = new Set(text.split(" "));
let unique = [];
for(let word of wordSet) {
unique.push(word);
}
console.log(unique); // => ["oh", "no", "way"]
let m = new Map([[1, "one"]]);
for(let [key, value] of m) {
key // => 1
value // => "one"
}
for(let p in o) { // Assign property names of o to variable p
console.log(o[p]); // Print the value of each property
}
let o = { x: 1, y: 2, z: 3 };
let a = [], i = 0;
for(a[i++] in o) /* empty */; //empty body statement
console.log(a); // => ["x", "y", "z"]
let o = { x: 1 };
o.propertyIsEnumerable("x") // => true: o has an own enumerable property x
o.propertyIsEnumerable("toString") // => false: not an own property
Object.prototype.propertyIsEnumerable("toString") // => false: not enumerable