各方法比较
方法 | 优劣 |
---|---|
for循环 | 最基础,对数组的可操作空间大。 |
forEach() | 使用方便,性能比for循环弱, break, continue无法使用 |
for...of | 性能高于for...in,遍历的是值(ES6) |
for...in | 效率较低,遍历的是索引 |
map() | 对数组进行整体操作时比较方便,返回一个新数组 |
filter() | 筛选 |
1. for循环
for(let i=0 len=arr.length; i<len;i++){
console.log(arr[i])
}
2. forEach()
数组自带方法,使用方便
// forEach()接收的参数:value数组中的当前项, index当前项的索引, array原始数组
arr.forEach(element => {
console.log(element)
});
arr.forEach((a, b, c) => {
console.log(b,a)
});
3. for...of循环
// 返回值
for (let item of arr){
if (item == 2) continue;
console.log(item)
}
4. for...in循环
// 返回键
for (index of arr){
console.log(index: arr[index])
}
5. map()
// 返回新的数组,不改变原数组,也就是原数组被“映射”成对应新数组。
let arr1 = arr.map((a,b,c) =>{
console.log(a*2)
return a
})
console.log(arr1)
6. filter()
console.log(arr.filter(a => parseInt(a)>0))