遍历的方法
1.基础方法1501ms
function sum(arr) {
let sumArr = 0;
for(i = 0; i < arr.length;i++){
sumArr += arr[i];
}
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
2.时间:1421ms
function sum(arr) {
let sumArr = 0;
let len = arr.length;//使用变量接收 arr.length,避免反复求取数组长度
for(i = 0; i < len; i++){
sumArr += arr[i];
}
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
3.forEach,时间 952ms
function sum(arr) {
let sumArr = 0;
arr.forEach(function(item, index, array){ //.forEach(function(item, index, array)函数中,第一个参数是遍历的值,第二个是 索引,第三个是数组本身
sumArr += item
})
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
4.forEach()中使用箭头函数 时间:960ms
function sum(arr) {
let sumArr = 0;
arr.forEach((item, index, array) => {
sumArr += item
})
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
5.map函数 时间 950ms
function sum(arr) {
let sumArr = 0;
arr.map(function(item, index){
sumArr += item
})
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
6. map函数中使用箭头函数 时间 1310ms
function sum(arr) {
let sumArr = 0;
arr.map((item, index) => { //.map(function(item, index)函数中,第一个参数是遍历的值,第二个是索引,第三个是数组本身
sumArr += item
})
return sumArr
}
let arr = [ 1, 2, 3, 4 ]
console.log(sum(arr))
*****补充数组的几个方法
1. arr.filter(function(item, index)) 过滤出符合条件的元素并返回一个新数组
2. arr.map(function(item, index)) 遍历每一个元素并且返回对应的元素(可以返回处理后的元素) (map 映射 一一 对应)
返回的新数组和旧数组的长度是一样的
使用比较广泛,但其性能还不如 forEach
3. arr.join()返回一个拼接的字符串