for…in
枚举对象的属性,也可以枚举从原型继承的属性
let _obj={name:'xiaoming',age:10}
for(let key in _0bj){
console.log("key",key) //name,age
}
let _arr=[1,2,3,4,5,6]
for(let key in _arr){
console.log("key",key) //0,1,2,3,4,5
}
注:for…in用于遍历数组时,可以将数组看作对象,数组下标看作属性名。但用for…in遍历数组时不一定会按照数组的索引顺序。
for of
使用for…of循环时,获得的是数组的元素值。for…of遍历Map时,可以获得整个键值对对象。
let arr=[1,2,3,4,5,6]
for(let key of arr){
console.log("key",key) //1,2,3,4,5,6,
}
OR
let arr=[{name:'xiaohong',age:11}]
for(let key of arr){
console.log("key",key) //{name:'xiaohong',age:11}
}
OR
let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let entry of iterable) {
console.log(entry); //["a", 1] ["b", 2] ["c", 3]
}
forEach遍历数组,但不能使用break、continue和return语句
let arr=[1,2,3,4,5,6]
arr.forEach((v,index)=>{
//v---1,2,3,4,5,6
//index--0,1,2,3,4,5
})