1.for循環
for(var i= 0 ; i<10; i++){
console.log('這個內容會打印10次')
}
for in
-
for in 多用於循環遍歷對象的屬性
-
循環出來的是key
-
for in 不適合遍歷數組 : 因為V的值不是數字類型 而是字符串類型,在進行字符串運算時會帶來極大的不便.
-
var myarr = [10,20,40,70];
for (v in myarr){
console.log(v); //1
console.log(typeof v); //string
}
•
#### for of
+ for of 多用於遍歷數組
+ 循環出來的是value
```javascript
var myarr = [10,20,40,70];
for (v in myarr){
console.log(v); //10
console.log(typeof v); //num
}
2.forEach()
-
參數1 callback
-
參數1:循環的當前元素
-
參數2 :當前元素的下標
-
參數3:當前元素所屬數組的對象
-
-
參數2 :可選。傳遞給函數的值一般用 "this" 值。如果這個參數為空, "undefined" 會傳遞給 "this" 值
var myarr = ['10','20','40','70'];
var otherArr = ['2','3']
myarr.forEach(function (v,i,) {
console.log(v) //value值
console.log(i) //相應的下標
console.log(this) //this指向foreach的參數2
},otherArr);
3.map() 兼容問題 但是很屌就對了!!
-
方法創建一個新數組,其結果是該數組中的每個元素都調用一個提供的函數后返回的結果。
-
參數1 callback
-
參數1:循環的當前元素
-
參數2 :當前元素的下標
-
參數3:當前元素所屬數組的對象
-
-
參數2 :可選。傳遞給函數的值一般用 "this" 值。如果這個參數為空, "undefined" 會傳遞給 "this" 值
var myarr = ['10','20','40','70'];
console.log(myarr.map(x => x * 2)); // ['20','40','80','140']
-
forEach()和map()遍歷
共同點
1.都是循環遍歷數組中的每一項。
2.forEach() 和 map() 里面每一次執行匿名函數都支持3個參數:數組中的當前項item,當前項的索引index,原 始數組input。
3.匿名函數中的this都是指Window。
4.只能遍歷數組。
4.some()
-
some()方法用於檢測數組中的元素是否滿足指定條件
-
該方法會依次執行數組中的每個元素
-
如果有一個元素滿足條件則返回true,剩余元素不會再次執行檢測
-
如果沒有滿足條件則返回false
-
不會對空數組進行檢測
-
不會改變原數組
-
-
var age = [4,12,18,20,21];
var judge = age.some(function(v){ //遍歷age中的value值 大於20則返回ture反之返回false
return v>20;
})
console.log(judge); //true
5.filter()
-
語法
-
array.filter(function(v,i,arr), thisValue)
-
-
創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
-
filter() 不會對空數組進行檢測。
-
filter() 不會改變原始數組。
-
var age = [4,12,18,20,21,23,99,'wo'];
var judge = age.filter(function(v){
return v>20;
})
console.log(judge); [21,23,99]