1.for-of与for-in遍历数组的区别
for-in语句是一种严格的迭代语句,用于枚举对象中的非符号键属性
for-of语句是一种严格的迭代语句,用于枚举可迭代对象的元素
<script>
console.log('for-in显示内容:');
let arr = [1,2,3,4,5,6];
for (const key in arr) {
console.log(key + ':' + arr[key]);
}
console.log('-----------------------------');
for (const iterator of arr) {
console.log(iterator);
}
</script>
for-in语句可以得到数组的索引号(key)与相应的值(arr[key]),而for-of语句只将arr数组中的元素迭代完,将值枚举出来
即:for-in遍历的是数组的键值(索引号),for-of遍历的是数组的值
2.for-of与for-in遍历对象
<script>
let obj = {
name:'张三',
age:'18',
}
console.log('for-in显示内容:');
for (const key in obj) {
console.log(key+':'+obj[key]);
}
console.log('-----------------------------');
console.log('for-of显示内容:');
for (const iterator of obj) {
console.log(iterator);
}
</script>
输出也能说明for-in遍历的是键值,通过键值遍历对象属性值,for-of不能遍历对象
总结:for-in遍历的是键值(索引号),for-of遍历的是元素值且不能用来遍历对象