1、ES5中数组的3中遍历方法
- forEach, forEach不支持break和continue
const arr = [1,2,3,4,5]
arr.forEach(function (item) {
//forEach遍历语法很简洁,但是break,continue失效了
console.log(item)
})
- every
const arr = [1,2,3,4,5]
arr.every(function (item) {
if(item === 4){
return false
}
console.log(item)
return true
//默认是返回return false,只能打印一个值,return true才能继续打印下去
})
- for in ,for in其实是遍历对象的,for in支持break和continue,但是index是个字符串
//for in遍历
const arr = [1,2,3,4,5]
for(let index in arr){
if(index == 2){ //注意此处的index是字符串,不能使用===,index是字符串!
break
}
console.log(index, arr[index])
}
2、ES6中的for of遍历数组
//for of遍历
for(let item of arr){
console.log(item)
}
3、ES5和ES6中分别将伪数组转化为数组
伪数组:{0:‘a’,1:‘b’,length:2},伪数组是一个对象,其中有length属性,其他属性按索引存储数据
ES5中:
let imgs = [].slice.call(document.querySelectorAll(‘img’)) // NodeList
ES6中:
let imgs = Array.form(document.querySelectorAll(‘img’))
Array.from()还具备遍历功能
let array = Array.from({length:5},function () {
return 1
})
console.log(array) //输出[1,1,1,1,1]
4、生成新数组
let array2 = Array.of(1,2,3,4,5)
或者Array.fill(value,start,end)也行
let array3 = Array(5).fill(5) //[5,5,5,5,5]
let array4 = [1,2,3,4,5]
console.log(array4.fill(-1,1,4)) //[1,-1,-1,-1,5]
5、数组的查找
- Array.filter()
//数组的查找
let array5 = [1,2,3,4,5]
let find = array5.filter(function (item) {
return item === 3
})
console.log(find) // [3]
如果要查数组中是否存在某元素,即使找到了,也不会停止,他会继续往下找,直至遍历整个数组,最终返回的为数组形式,如果数组较长,效率是较低的。在ES6中可使用查找
- Array.find()
let find2 = array5.find(function (item) {
return item === 2
})
//如果找到,返回值(不是返回数组),如果没有找到,返回undefined
filter()会找到所有的符合的值组成一个数组返回,find找到第一个符合的值返回