Loop through an array or an object up for, forEach, for in, for of use
for loop
Since the birth Javascript there, through the array, for loop syntax is as follows:
for (statement 1; statement 2; statement 3) {
block of code to be executed
}
for example
var arr = [1,2,3,4]
for(var i = 0 ; i< arr.length ; i++){
console.log(arr[i]); // 1 2 3 4 (输出结果)
}
forEach loop
ES5 built from the beginning Javascript method forEach iterate
ARR = the let [ 'A', 'B', 'C', 'D']
arr.forEach (function (Val, IDX, ARR) {
the console.log (Val + ', index =' + IDX) // Val is the current element, index index of the current element, arr array
the console.log (ARR)
})
Output
a, index = 0
(4) ["a", "b", "c", "d"]
b, index = 1
(4) ["a", "b", "c", "d"]
c, index = 2
(4) ["a", "b", "c", "d"]
d, index = 3
(4) ["a", "b", "c", "d"]
Writing a lot simpler, but there is a limitation that you can not break the cycle (or use the break statement using a return statement).
for in loop
for-in loop to actually loop "enumerable" objects designed
{A obj = the let: '. 1', B: '2', C: '. 3', D: '. 4'}
for (in the let O obj) {
the console.log (O) // objects actually traversed attribute names a, B, C, D
the console.log (obj [O]) // this is the attribute value corresponding 1,2,3,4
}
for - in it can also be used to loop through the array, but generally not recommended
for of loop
It is ES6 newly added syntax
An array cycle
let arr = ['China', 'America', 'Korea']
for (let o of arr) {
console.log(o) //China, America, Korea
}
But it does not loop a normal object
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of obj) {
console.log(o) //Uncaught TypeError: obj[Symbol.iterator] is not a function
}
However, an object can be recycled has enumerable properties.
If we circulate by property owned by the object, you can use the built-in Object.keys () method
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.keys(obj)) {
console.log(o) // a,b,c,d
}
If we attribute values owned by object circulated, you can use the built Object.values () method
let obj = {a: '1', b: '2', c: '3', d: '4'}
for (let o of Object.values(obj)) {
console.log(o) // 1,2,3,4
}
A string loop
let str = 'love'
for (let o of str) {
console.log(o) // l,o,v,e
}
Circulating a Map
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
for (let entry of iterable) {
console.log(entry);
}
// [a, 1]
// [b, 2]
// [c, 3]
Set a loop
let iterable = new Set([1, 1, 2, 2, 3, 3]);
for (let value of iterable) {
console.log(value);
}
// 1
// 2
// 3
A circular array of type
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) {
console.log(value);
}
// 0
// 255