共计 880 个字符,预计需要花费 3 分钟才能阅读完成。
const arr = [1, 2, 3]; | |
// for 循环: 可能应用 break, continue, return 管制循环; 通过下标间接拜访元素 | |
for (let index = 0; index < arr.length; index++) {const element = arr[index]; | |
console.log(element); | |
} | |
// forEach: 不能应用 break, continue 管制循环(函数的本意就是要遍历每个元素), 然而能够应用 return 成果相当于 continue(不倡议在该函数中应用)arr.forEach((value, index) => {if (value == 2) {return false;} | |
// console.log(value); | |
}); | |
// for-in: 最好用于遍历对象, 反对 break 和 continue, return 终止循环 | |
for (const key in arr) {if (arr.hasOwnProperty(key)) {const element = arr[key]; | |
// if(element === 2){ | |
// break; | |
// } | |
console.log(element); | |
} | |
} | |
// for-of: 专门为数组设计的遍历办法, 间接遍历其属性, 反对 break 和 continue, return 终止循环 | |
// 也能够遍历具备 Symbol.iterator 接口的任何数据结构 | |
for (const item of arr) {if(item === 2){continue;} | |
// console.log(item); | |
} | |
const iterator = arr[Symbol.iterator](); | |
while(true){const next = iterator.next(); | |
if(next.done){break;} | |
// console.log(next.value); | |
} | |
// every: 变相遍历数组 | |
arr.every((value, index) => {// console.log(index, value); | |
return true; // 返回真值持续下次循环等同于 continue, 返回假值完结循环等同于 break | |
}); |
正文完
发表至: javascript
2020-11-18