var arr = [ 1, 5, 8, 10, 24 ]
1.for循环
for(var i = 0; i < arr.length; i++) {
console.log(arr[i]) // 1, 5, 8, 10, 24
}
2.forEach循环( 找到第一个符合条件也不会终止执行,没有返回值 )
arr.forEach((item, index, arr) => {
// item是每个数组的值,index是 索引号,arr是数组本身
console.log('index:' + index + ',' + 'item:' + item)
// index: 0, item: 1
// index: 1, item: 5
// index: 2, item: 8
// index: 3, item: 10
// index: 4, item: 24
})
3、map循环( 返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值 )
var res = arr.map(function (item,index,arr ) {
return item*10;
})
console.log(res) // var res = [ 10, 50, 80, 100, 240 ]
4、for of 遍历 ( 可以用break来终止整个循环,或者continute来跳出当前循环,继续后面的循环 )
for (var item of arr) {
console.log(item) // 1 5 8 10 24
}
5、filter 遍历 ( 找到第一个符合条件也不会终止执行,不会改变原始数组,返回新数组 )
var newArr = arr.filter(item => item > 5)
console.log(newArr) // 得到新数组 [ 8, 10, 24 ]
6、every 遍历 ( 返回一个布尔值,所有元素都满足条件返回true,只要有一个不满足则返回false )
var bool = arr.every(( item, index, array ) => {
return item > 8;
})
console.log(bool) // false
this.disableds = goodsList.every(item => {
return item.refundCount == item.inputNum
})
7、some 遍历 ( 返回一个布尔值,只要有一个满足条件的就返回true,如果所有都不满足则返回false )
var bool = arr.some (( item, index, array ) => {
return item > 3;
})
console.log(bool) // true
8、find ( 返回第一个满足过滤方法的元素,一个都没有满足的就返回undefined,遇到一个满足的元素后遍历就停止了 )
**这个方法支持的浏览器太少,慎用
var arr1 = arr.find(( item, index, array ) => {
return item > 1;
})
console.log(arr1) // 5
9、findIndex ( 只要有一个元素返回 true,findIndex 立即返回该返回 true 的元素的索引值。如果数组中没有任何元素返回 true,则返回 -1 )
var index = arr.findIndex((item, index, array) => {
return item > 5;
})
console.log(index) // 2 ( 索引值 )
10、keys,values,entries
// keys 对键名的遍历
for (let index of arr.keys()) {
console.log(index) // 0 1 2 3 4
}
// values 对键值的遍历 对键值对的遍历
for (let index of arr.values()) {
console.log(index) // 1 5 8 10 24
}
// entries
for (let index of arr.entries()) {
console.log(index)
// 0 1
// 1 5
// 2 8
// 3 10
// 4 24
}
11、includes 表示某个数组是否包含给定的值,返回布尔值
var arr1 = arr.includes('a')
console.log(arr1) // true 找到了给定的值则返回true,反之为false
12、for in ( 不建议使用 )
13、jquery 的 $each
14、reduce