for in array code example
Example 1: javascript loop through array
const myArray = ['foo', 'bar'];
myArray.forEach(x => console.log(x));
for(let i = 0; i < myArray.length; i++) {
console.log(myArray[i]);
}
Example 2: loop an object in javascript
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
Example 3: for of js
let list = [4, 5, 6];
for (let i in list) {
console.log(i);
}
for (let i of list) {
console.log(i);
}
Example 4: for in javascript
const object = {a: 1, b: 2, c: 3};
for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
Example 5: for of js
let panier = ['fraise', 'banane', 'poire'];
for (const fruit of panier) {
console.log(panier.indexOf(fruit));
}
Example 6: for in loop javascript
var person = {"name":"taylor","age":31};
for (property in person) {
console.log(property,person[property]);
}