for.....in.....和for....of.....同异
一、相同点
(1)能遍历
二、不同点
(1)返回值不同。
for....in..... : 返回的是key
for.....of...... :返回的是value
const arr = ['a','b']; for(let i in arr){ console.log(i);// 1 2 } for(let i of arr){ console.log(i);// a b }
(2)遍历对象不同。
for.....in....... :主要是给对象使用的。虽然数组也可以使用,但是会有很多的问题(下标类型被当成字符串;即使下标不是数字,同样参与了遍历),造成这些问题的原因还是for....in.....把数组当对象进行处理了。
for.....of...... :给有Interator接口的数据结构使用的。因为对象没有Interator接口,所以不能遍历。
const obj = {id:1,name:"zheng"};
for (let key in obj) {
console.log(key); // id name
}
for (let value of obj) {
console.log(value); // 报错 Uncaught TypeError: obj is not iterable
}
const arr = ['a','b'];
arr.name = "zheng";
for (let key in arr) {
console.log(key); // 0 1 name
console.log(typeof key);//string string string
console.log(arr[key]);// a b zheng
}
for (let value of arr) {
console.log(value); // a b
}

浙公网安备 33010602011771号