<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>for-of遍历</title>
</head>
<body>
<script>
let arr = [1, 2, 3, 4]
let obj = {
name: 'obj',
age: 18
}
arr.desc = 'arr'
// for of
for (let item of arr) {
console.log(item)
}
// for of 不支持 遍历 obj 对象
// for(let item of obj){
// console.log(item)
// }
// for in
for (let item in arr) {
console.log(item)
}
// for-of 与 for-in 的区别
// 1、使用范围:for-of 不能用于遍历对象;而 for-in 可以;
// 2、遍历结果: for-of 遍历结果是 value; 而 for-in 遍历结果是 key;
// 3、遍历的范围:for-of遍历范围是 键为数字(key为数字); 而 for-in 遍历的范围是 对象上 可以一切可遍历的;
// forEach 遍历
let fruits = ['apple', 'orange', 'banana']
fruits.forEach(item => {
if (item === 'orange') {
break // 报错
}
console.log(item)
})
for (let item of fruits) {
if (item === 'orange') {
continue
}
console.log(item)
}
// for-of 和 forEach 的区别
// for-of 可以被 break/continue ; 而 forEach 不可以,会报错
</script>
</body>
</html>