for-in (获取对象或数组的key值)
对数组使用
let arr = ['a',123,{a:'1',b:'2'}];
for(let index in arr){
console.log(arr[index]);
}
// 0 1 2
for(let index in arr){
console.log(arr[index]);
}
// a 123 {a: "1", b: "2"}
对普通对象使用
let obj = {a:1,b:2}
for(let i in obj){
console.log(i);
}
// a b
for-of (获取数组的值 不可用于普通对象)
对数组使用
let arr = ['a',123,{a:'1',b:'2'}];
for(let index in arr){
console.log(arr[index]);
}
// a 123 {a:"1",b:"2"}
对普通对象使用
let obj = {a:1,b:2}
for(let i of obj){
console.log(i);
}
// Uncaught TypeError: obj is not iterable
new Set()
虽然实际是object 但是当做数组来看比较好理解
let set = new Set([1,2,3,4]);
for(let i in set.value()){
console.log(i);
}
// 无法进行遍历
for(let i of set.values()){
console.log(i);
}
// 1 2 3 4
// Set 结构的实例默认可遍历,它的默认遍历器生成函数就是它的values方法 所以也可以这样写。
for(let i of set){
console.log(i);
}
// 1 2 3 4
总结
普通对象 用for-in
数组 要用key就用for-in 不用key就用for-of可以直接获取values
new Set类型 用for-of(暂时不知道for-in为什么不可以)