代码:
<script> //数组遍历 let arr = ["a", "b", "c"]; arr[3] = "d"; for (let item in arr) { console.log(item); } //结果 0 1 2 3 for (let item of arr) { console.log(item); } //结果是a b c d//对象遍历 let obj = { a: "小明", b: "小红", c: "小兰" }; obj.d = "小王"; for (let item in obj) { console.log(item); } //获得key值: a b c d
for (let item of obj) { //对象不能使用of console.log(item); } //Uncaught TypeError: obj is not iterable </script>
in用来循环对象并获得key值,循环数组获得索引
of用来循环数组得到数组中的值