javascript循環(huán)

——這篇文章主要介紹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ù)組弊端
  1. 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
  1. 不僅數(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容