Javascript中的遍歷循環
1.for循環
對于數值索引的數組來說,可以使用標準的for循環來遍歷值
1
2
3
4
|
const arr=[1,2,3,4]; for (let i=0;i<arr.length;i++){ console.log(i); } |
2.for...in循環
for...in循環可以用來遍歷對象的可枚舉屬性列表(包括原型鏈上的屬性)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
const myObject={}; Object.defineProperty(myobject, "a" ,{ //可枚舉 enumerable: true , value:2, }) Object.defineProperty(myobject, "b" ,{ //不可枚舉 enumerable: false , value:2, }) for (let k in myObject){ console.log(k,myObject[k]) // a 2 } //使用for...in循環是無法直接獲得屬性值的,因為它實際遍歷的是對象中的所有可枚舉屬性, //所以你需要手動獲得屬性值. |
在數組上應用for...in循環,不僅僅會包含所有數值索引,還會包含所有可枚舉屬性.
所以最好在對象上應用for...in循環。如果要遍歷數組最好使用傳統的for循環來遍歷.
3.for...of循環
1.ES6新增的for...of循環
1
2
3
4
5
6
7
|
const arr=[1,2,3]; for (let value of arr){ console.log(value) //1 //2 //3 } |
for...of循環首先會向所有被訪問的對象請求一個迭代器對象,然后通過調用迭代器對象的next()方法來遍歷所有返回值
在數組中有內置的@@iterator,因此for...of可以直接應用在數組上。
使用內置的@@iterator遍歷數組
1
2
3
4
5
6
7
8
9
10
11
12
|
const arr=[1,2,3]; //獲取數組中的iterator對象:使用ES6中的符號Symbol.iterator來獲取對象的@@iteraotr內部屬性. //@@iterator本身不是一個迭代器,而是一個返回迭代器對象的函數。 const it=arr[Symbol.iterator](); it.next(); //{value:1,done:false} it.next(); //{value:2,done:false} it.next(); //{value:3,done:false} it.next(); //{done:true} //調用迭代器的next()方法會返回形式為{value:..,done:..}的值; //value為當前的值,done是一個布爾值,表示是否還存在可以遍歷的值 |
2.給對象定義@@iterator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
const myObject={ a:2, b:3 } Object.defineProperty(myObject,Symbol.iterator,{ enumerable: false , writeable: false , configurable: true , value: function (){ let o= this ; let idx=0; //對象中的屬性數組 let ks=Object.keys(o); return { value:o[ks[idx++]], done:(idx>ks.length); } } }) const it=myObject[Symbol.iterator](); it.next(); //{value:2,done:false} it.next(); //{value:3,done:false} it.next(); //{done:true} for (let value of myObject){ console.log(value); } // 2 // 3 |
4.foreach(...)
**forEach()**
方法對數組的每個元素執行一次給定的函數。
1
2
3
4
5
|
const arr = [ 'a' , 'b' , 'c' ]; arr.forEach(element => console.log(element)); // a // b // c |
1
|
arr.forEach(callback(currentValue [,index [,array]])[,thisArg]) |
5.some(...)
some()是對數組中每一項運行給定函數,如果該函數對任一項返回true,則返回true。
1
2
3
4
5
6
7
8
9
10
11
|
var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.some( function ( item, index, array ){ console.log( 'item=' + item + ',index=' +index+ ',array=' +array ); return item > 3; })); // item=1,index=0,array=1,2,3,4,5,6 // item=2,index=1,array=1,2,3,4,5,6 // item=3,index=2,array=1,2,3,4,5,6 // item=4,index=3,array=1,2,3,4,5,6 // true |
6.every(...)
every()是對數組中每一項運行給定函數,如果該函數對每一項返回true,則返回true。
1
2
3
4
5
6
7
8
|
var arr = [ 1, 2, 3, 4, 5, 6 ]; console.log( arr.every( function ( item, index, array ){ console.log( 'item=' + item + ',index=' +index+ ',array=' +array ); return item > 3; })); // item=1,index=0,array=1,2,3,4,5,6 // false |
以上就是JavaScript 中的六種循環方法的詳細內容,更多關于JavaScript 循環的資料請關注服務器之家其它相關文章!
原文鏈接:https://juejin.cn/post/6914158102254190605