// for in traversal is the index of the array (ie, keys), while for of traverse is an array element value.
let arr = [1,2,3,4,5,6,7]
for(let index of arr){
// console.log(index)//1 2 3 4 5 6 7
}
for(let index in arr){
// console.log(index)//0 1 2 3 4 5 6
//console.log(arr)//1 2 3 4 5 6 7
//console.log(arr[index])
}
// traverse the object is usually used for in the keys to traverse the object
let obj = {
a:1,
b:2,
c:3
}
for(let key in obj){
console.log(key)//a b c
//console.log(obj[key])//1 2 3
}
forEach
- Three parameters, a first value, the second index, the third array thereof.
- It applies to an array, set, map, not suited to the string, Object.
- You can not modify and delete data collections, for the same efficiency and recycling, do not care about the next set of target returns.
- You can not terminate the loop, break, continue not be used.
chestnut:
let arr = [1, "ding", null, 5, true, undefined];
arr.forEach(function (value, index, a) {
console.log("value:", value, "index:", index, "a:", a);
})
for in
- Index to a string
- Used for traversing the object, json, arrays, no order, increasing the conversion process so overhead is relatively large
- Can be extended attributes will traverse
- Support break, continue
chestnuts:
for (let item in obj) {
console.log(item, ":", obj[item]);
if (item == "age") delete obj [item]; // delete attribute success
}
console.log("obj:", obj);
- Is the best way through the array, may be used in the set, map, array type, the string, but does not support native Object traversal.
- Support break, continue