——這篇文章主要介紹javascript中幾大循環(huán)的區(qū)別
最原始的js循環(huán)
es5出現(xiàn)以前,我們要遍歷一個(gè)數(shù)組時(shí),是這樣寫的
let arr = [{a: 1}, {a: 2}, {a: 5}]
for (let i = 0; i < arr.length; i++) {
console.log(arr[index])
}
es5的循環(huán)
自從es5誕生以后,多了兩個(gè)循環(huán),forEach和for in,接下來分別介紹這兩個(gè)循環(huán)
1. forEach
let arr = [{a: 1}, {a: 2}, {a: 5}]
arr.forEach((item, index, arr) => {
console.log(item, index, arr)
if (item.a === 2) {
console.log(‘中斷’)
return
}
console.log(‘測試中斷’)
})
forEach的寫法比原始的for循環(huán)簡單了很多,我們也不需要定義一個(gè)變量去做循環(huán)。使用forEach不能用 break和continue中斷循環(huán),使用return也只能終止本次循環(huán),不能中斷整個(gè)循環(huán)語句。
2. for in
用for in 來遍歷對象
var obj = {a: 1, b: 5, c: 7}
for (let key in obj) {
console.log(`obj.${key} = ${obj[key]}`)
}
for in除了可以遍歷對象,也可以用來遍歷數(shù)組
let arr = [{a: 1}, {a: 2}, {a: 5}]
for (let i in arr) {
console.log(arr[i])
}
for in 寫法比原始的for循環(huán)簡單了寫,也彌補(bǔ)了forEach的缺陷。但是for in 一般是用來遍歷對象,不推薦用來遍歷數(shù)組。
for in 遍歷數(shù)組弊端
- for (let index in arr) 中index的類型不是number,而是string
let arr = [{a: 1}, {a: 2}, {a: 5}]
for (let index in arr) {
console.log(index + 1)
}
// 01
// 11
// 21
- 不僅數(shù)組本身的元素將被遍歷到,自定義的屬性也會(huì)被遍歷到,甚至數(shù)組原型鏈上的屬性也會(huì)被遍歷到
var arr=new Array(1,2,3);
arr.name="hello";
Array.prototype.method=function(){
console.log("world");
}
for (var index in arr) {
console.log(index);
}
// 0
// 1
// 2
// name
// method
es6的循環(huán)
for of
es6中引入了一種新的循環(huán)方法,它就是for-of循環(huán),它既比傳統(tǒng)的for循環(huán)簡潔,又彌補(bǔ)了forEach和for-in循環(huán)的弊端。
let arr = [{a: 1}, {a: 2}, {a: 5}]
for (let itemof arr) {
console.log(item)
}
寫法上 for of 和 for in 很相似,但是for of 的功能更加豐富
1. 循環(huán)數(shù)組
let arr= [10, 40, 70];
for (let value of arr) {
console.log(value);
}
// 10
// 40
// 70
2. 循環(huán)字符串
let str= "this";
for (let value of str) {
console.log(value);
}
// t
// h
// i
// s
3. 循環(huán)一個(gè)map
let map= new Map([["a", 1], ["b", 2], ["c", 3]]);
for (let [key, value] of map) {
console.log(key, value);
}
// a 1
// b 2
// c 3
for (let item of map) {
console.log(item);
}
// [a, 1]
// [b, 2]
// [c, 3]
4. 遍歷一個(gè)對象
for of 不能像for in那樣直接遍歷一個(gè)對象,我們可以用Object.keys()方法去解決這個(gè)問題
let obj = {a: 12, b: 56, c: 89}
for (let key of Object.keys(obj)) {
console.log(`${key} = ${obj[key]}`)
}
// a = 12
// b = 56
// c = 89
5.遍歷一個(gè) Set
let set= new Set([1, 1, 2, 2, 3, 3]);
for (let value of set) {
console.log(value);
}
// 1
// 2
// 3