JS循環遍歷方法總結

經常使用的循環遍歷方法

  1. for()循環
  2. forEach
  3. map()
  4. for..in
  5. for..of
  6. jquery:$.each()

forEach() & map()

forEach(),map()是es5新增的循環遍歷方法。
jquery

相同點:es6

1.寫法類似數組

arr.forEach(function(item,index,arr){...})

arr.map(function(item,index,arr){...})

 item: 元素
index: 元素索引
  arr: 數組自己複製代碼

2.都只能遍歷數組bash

3.匿名函數中的this都指向windowdom

[1,2].forEach(function(item,index,arr){console.log('this指向:',this);})

  this指向: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
  this指向: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
[1,2].map(function(item,index,arr){console.log('this指向:',this);})

this指向: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}
this指向: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …}複製代碼

4. 在forEach和map中,不能使用 continue 和 break ,可使用 return 或 return false 跳出循環,效果與 for 中 continue 同樣。可是即便使用return跳出循環,也不能一次結束全部循環。相似於continue。函數



[1,3,4,24,5,6].forEach(function(item){if(item === 24){return;} console.log(item);})   
  =>
  1
  3
  4
  5
  6

[1,3,4,24,5,6].map(function(item){if(item === 24){return;} console.log(item);})   
=>
1
3
4
5
6複製代碼


不一樣點:
post

   map()返回一個新數組,而且不會改變原數組的值.map()這類是轉換型函數,須要關心返回值。ui

   forEach()沒有返回值,也不改變原數組this

   

var arr = [1,2,3,4,5];
var add = arr.map(function(item){
   return item + 1;
})
=> 
add: [2, 3, 4, 5, 6]
arr: [1, 2, 3, 4, 5]

var add2 = arr.forEach(function(item){
   return item + 1;
})
=>
add2: undefined
arr: [1, 2, 3, 4, 5]複製代碼


for...in() & for...of()

相同點:es5

1.匿名函數中的this都指向window

2.都是用break來跳出循環,中斷全部。

不一樣點:

for..in 是es5新增的循環方法 。

for..of是es6新增的循環方法。

for..in: 遍歷對象的key值,訪問對象的可枚舉屬性。有點相似於Object.keys()

var obj={a:'1',b:'2',c:'3'};
for(item in obj){
    console.log(item);
}
=>
a
b
c

補充:
var a = Object.keys(obj)
a=>["a", "b", "c"]

var b = Object.values(obj)
b => ["1", "2", "3"]
複製代碼

for...in遍歷數組時,返回數組的下標,可經過下標訪問元素,而且for--in返回的是string類型!

var arr = ['a','b','c'];
for(item in arr){
    console.log(item,arr[item],typeof(item));          //可經過arr[item]訪問元素
}
=>
0 a string
1 b string
2 c string複製代碼

for..in使用break跳出循環,中斷全部。

var arr = ['a','b','c'];
for(item in arr){
if(item === '1'){return}
    console.log(item,arr[item],typeof(item));        
}

=>0 a string複製代碼

for...of

es6引入了新的iterable(迭代)類型,Array,Map,Set都屬於iterable類型。

具備iterable類型的集合能夠經過for..of循環來遍歷

for..of可用break來中斷循環,而且可中斷全部循環,不能用return/return false!


var a = ["a","b","c"];
var s = new Set(["a","b","c"]);
var m = new Map([[1,"x"],[2,"y"],[3,"z"]]);

a=>
(3) ["a", "b", "c"]

s=>
Set(3) {"a", "b", "c"}

m=>
Map(3) {1 => "x", 2 => "y", 3 => "z"}

-----------------------------------------------------------
for (var item of a){
      console.log(item);
}
=>
a
b
c
------------------------------------------------------------
for (var item of s){
      console.log(item);
}
=>
a
b
c
-----------------------------------------------------------
for (var item of m){
     console.log(item[0]+ "=" + item[1]);
}
=>
1=x
2=y
3=z


複製代碼

iterable類型也能夠用forEach: 

Set: 

var s = new Set(["A","B","C"]);
s
=> Set(3) {"a", "b", "c"}

s.forEach((item,index,arr)=>{
    console.log('item',item);
    console.log('index',index);        //Set沒有索引,所以回調函數的前兩個參數都是元素自己;
    console.log('arr',arr)})               
=>
item a
index a
arr Set(3) {"a", "b", "c"}

item b
index b
arr Set(3) {"a", "b", "c"}

item c
index c
arr Set(3) {"a", "b", "c"}複製代碼

Map

var m = new Map([[1,'x'],[2,'y'],[3,'z']])
m
=> Map(3) {1 => "x", 2 => "y", 3 => "z"}

m.forEach((item,index,arr)=>{
    console.log('item',item);                   //Map的回調函數參數依次是value、key和m自己。
    console.log('index',index);
    console.log('arr',arr)})
=>
item x
index 1
arr Map(3) {1 => "x", 2 => "y", 3 => "z"}

item y
index 2
arr Map(3) {1 => "x", 2 => "y", 3 => "z"}

item z
index 3
arr Map(3) {1 => "x", 2 => "y", 3 => "z"}複製代碼

break中斷for..of循環

var a = ["A","B","C"];
for (var x of a){
     if(x==='B'){break;} console.log(x);
}
=>
A複製代碼

jquery--$.each()

說到$.each()就要順便說一下$().each()

$().each()在dom上用的比較多

$("input[type='checkbox']").each(function(i){
  if($(this).attr('checked')==true){
    ........  }
}複製代碼

$.each(function(index,item){...})

$.each便可以遍歷數組,也能夠遍歷對象。

  匿名函數中的this指向當前元素

1.遍歷對象

var arr= ['a','b','c','d'];
var a = $.each(arr,function(index,item,arr){    //index:索引 item: 元素。
      console.log(index,item);
      console.log('this',this);  //this指向當前元素
})
=>
0 'a' this String {0: "a", length: 1, [[PrimitiveValue]]: "a"}
1 'b' this String {0: "b", length: 1, [[PrimitiveValue]]: "b"}
2 'c' this String {0: "c", length: 1, [[PrimitiveValue]]: "c"}
a=>
["a", "b", "c", "d"]
 返回的是arr自己,即便對item作修改。
 由於$.each()是消費型函數,不關心返回值,return的做用就是終止循環。
複製代碼

在$.each中,一樣是使用 return 或 return false 跳出循環,效果相似效果與 for 中 break,結束全部循環。

var arr2 = [1,2,3,4]
var b = $.each(arr2,function(index,item){
        if(item === 3){return false}
        console.log(item+1)
})
=>
2
3
b=>
[1, 2, 3, 4]
複製代碼

2.遍歷對象

$.each({a:'1',b:'2'}, function(index, item){
    console.log('key:',index,'value:','item')
})

=>
key: a value: item
key: b value: item
複製代碼

總結:

for()外,遍歷數組經常使用map(),forEach(),for..of,$.each()

遍歷對象經常使用for..in,$.each


只有$.each()匿名函數中this指向元素自己,其餘都指向window


map(),forEach()只能使用return跳出循環,只能跳出當前循環,相似continue

for..in,for..of用break跳出循環,跳出全部

$.each()只能使用return跳出循環,跳出全部,相似break


map(function(item,index,arr){})

forEach(function(item,index,arr){})

forEach(function(item,item,Set){})

forEach(function(value,key,Map))

for(item in obj){}/for(item in arr)

for(item of arr)

for(item of arr )


補充:從知乎上扒了張有意思的圖




ps:水平有限,若有錯誤,望指出。

相關文章
相關標籤/搜索