1.for in 和 for of 都可以循环数组,for in 输出的是数组的 index 下标,而 for of 输出的是数组的每一项的值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const arr = [1, 2, 3, 4, 5]
// for in
for (const index in arr) {
console.log(index); // 输出 0, 1, 2, 3, 4
}
// for of
for (const item of arr) {
console.log(item) // 输出 1, 2, 3, 4, 5
}
</script>
</body>
</html>
2.for in 可以遍历对象,for of 不能遍历对象,只能遍历带有iterator(迭代器)接口的,例如Set,Map,String,Array。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const object = { name: 'Jack', age: 18 }
// for ... in
for (const key in object) {
console.log(key) // 输出 name,age
console.log(object[key]) // 输出 Jack,18
}
// for ... of
for (const key of object) {
console.log(key) // 报错 Uncaught TypeError: object is not iterable
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// 使用for...of循环遍历Set实例的例子
const mySet = new Set([1, 2, 3, 4, 5]);
// 使用for...of循环遍历Set中的元素
for (const value of mySet) {
console.log(value); // 打印每个元素的值
}
// 使用for...of循环遍历Map对象的例子
const map = new Map();
// 添加键值对
map.set('key1', 'value1');
map.set('key2', 'value2');
map.set('key3', 'value3');
// 使用for...of遍历Map对象
for (const [key, value] of map) {
console.log(key + ' = ' + value);
}
</script>
</body>
</html>
3.数组对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const list = [{ name: 'Jack' }, { age: 18 }]
for (const val of list) {
console.log(val) // 输出 { name: 'Jack' },{ age: 18 }
for (const key in val) {
console.log(val[key]) // 输出 Jack,18
}
}
</script>
</body>
</html>
总结:for in 适合遍历对象,for of 适合遍历数组。for in 遍历的是数组的索引,对象的属性,以及原型链上的属性。