Javascript之遍歷數(shù)組方法
作者:前端程序猿
作為一個(gè)程序?qū)τ跀?shù)組遍歷大家都不是很陌生,再開發(fā)中我們也經(jīng)常要處理數(shù)組。這里我們討論下常用的數(shù)組遍歷方法和區(qū)別。
作為一個(gè)程序?qū)τ跀?shù)組遍歷大家都不是很陌生,再開發(fā)中我們也經(jīng)常要處理數(shù)組。這里我們討論下常用的數(shù)組遍歷方法和區(qū)別。
1.第一種for循環(huán)
- var arr = [1,2,3,4,5];
- for(var i=0,i<arr.length;i++){
- console.log("for循環(huán):"+arr[i]); //打印出1,2,3,4,5
- }
2.for ..in 遍歷方式
- // for in 遍歷需要兩個(gè)形參 ,index表示數(shù)組的下標(biāo)(可以自定義),arr表示要遍歷的數(shù)組
- var arr = [{num:1},{num:2},{num:3},{num:4},{num:5}];
- for(var index arr){
- console.log("index:"+index,"num:"+arr[index].num);// 依次打印出 index:0,num:1...
- }
3.forEach 遍歷方式
- var arr = [{num:1},{num:2},{num:3},{num:4},{num:5}];
- arr.forEach(function(item,index){
- console.log("index:"+index,"num:"+item.num); //同樣打印index:0,num:1...
- });
4.map 遍歷方式
- var list = [1, 2, 3, 4, 5];
- var arr = [];
- arr = list.map((value, index) => {
- return value * 2;
- });
- console.log(arr);//[2, 4, 6, 8, 10]
- 這里map和forEach在遍歷數(shù)組的區(qū)別就是map 有返回值,返回一個(gè)新的數(shù)組,而forEach沒有返回值
5.for-of遍歷方式
- var arr = [1,2,3,4,5];
- for(var value of arr){
- console.log("數(shù)組數(shù)據(jù):"+value); //1,2,3,4,5
- }
在這還有一個(gè)要想說的就是,在使用遍歷數(shù)組時(shí)候,如果想跳出遍歷return true fasle break沒有反應(yīng),這其實(shí)是使用的遍歷方法不對,當(dāng)想跳出循環(huán)可以使用every 和 some方法。
- //every()當(dāng)內(nèi)部return false時(shí)跳出整個(gè)循環(huán)(return true;也要寫入)
- let list = [1, 2, 3, 4, 5];
- list.every((value, index) => {
- if(value > 3){
- console.log(value); // 4
- return false;
- }else{
- console.log(value); // 1 2 3
- return true;
- }
- });
- ================================
- //some 當(dāng)內(nèi)部return true時(shí)跳出整個(gè)循環(huán)
- let list = [1, 2, 3, 4, 5];
- list.some((value, index) => {
- if(value === 3){
- return true; //當(dāng)內(nèi)部return true時(shí)跳出整個(gè)循環(huán)
- }
- console.log(value)// 1 2
- });
責(zé)任編輯:武曉燕
來源:
今日頭條