一、for/in
1、可以用来遍历对象和数组:遍历对象是key, 遍历数组是index(字符串类型)
2、for in会遍历对象或数组除Symbol类型以外的所有可枚举属性,包括原型。如果不想遍历原型方法和属性的话,可以在循环内部判断一下,使用hasOwnProperty()方法可以判断某属性是不是该对象的实例属性
// 遍历对象
const s1 = Symbol("symbol1")
const obj = { a: 1, b: 2, c: 3, [s1]: 4 }
for(let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
console.log(key); // a b c
}
}
// 遍历数组, index为字符串类型
const s1 = Symbol("symbol1")
const arr= [1, 2, 3]
arr[3] = 4
arr[s1] = 5
for(let index in arr) {
if (Object.hasOwnProperty.call(arr, index)) {
console.log(index); // 0 1 2 3
}
}
3、中断遍历 return / throw new Error()
const obj = { a: 1, b: 2, c: 3 }
for(let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
console.log(key); // a
return // 或者throw new Error()
}
}
// 下面代码不会执行,前面已经return
const array = [10, 20, 30];
for (const index in array) {
console.log(value);
}
二、for/of 【es6】
1、默认用来遍历可迭代对象(含Symbol.iterator属性方法)(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
2、遍历的只是数组内的元素,不包括原型属性和索引
// 迭代数组
const array = [10, 20, 30];
const iterator = arr[Symbol.iterator]()
for (const value of array) {
console.log(value); // 输出 10 20 30
}
// 迭代String
const string = 'hello'
const iterator = string[Symbol.iterator]()
for (const s of string) {
console.log(s); // 输出 h e l l o
}
// 迭代map
const map = new Map([["a", 1], ["b", 2], ["c", 3]]);
const iterator = map[Symbol.iterator]()
for (const item of map) {
console.log(item); // 输出 [ 'a', 1 ] [ 'b', 2 ] [ 'c', 3 ]
}
// 迭代set
const set = new Set([1, 1, 2, 2, 3, 3]);
const iterator = set[Symbol.iterator]()
for (let item of set) {
console.log(item); // 输出 1 2 3
}
3、中断遍历 return / throw new Error()
const array = [10, 20, 30];
for (const value of array) {
console.log(value); // 输出 10
return // 或者throw new Error()
}
// 下面代码不会执行,前面已经return
const string = 'hello'
for (const s of string) {
console.log(s);
}
三、for/of 自定义对象遍历
const obj = { a: 1, b: 2, c: 3 }
Object.prototype[Symbol.iterator] = function() {
const keys = Object.keys(this)
let index = 0
return {
next: () => {
const value = { key: keys[index], value: this[keys[index]] }
const done = index >= keys.length
index++
return {
value,
done
}
}
}
}
for (const iterator of obj) { // obj is not iterable
console.log(iterator);
}
四、小程序体验
![](https://img.haomeiwen.com/i3958254/81e376b9b3a0375e.jpg)
plan_up.jpg
网友评论