注:都不会对空数组进行操作,使用前要判空。
let arr = [12, 5, 8]
let result = arr.map(function (item) {
return item*2
})
console.log(result)//[24, 10, 16]
let result2 = arr.map(item=>item*2) // 简写
console.log(result2)//[24, 10, 16]
var arr = [1, 3, 5, 7]
var result = arr.reduce(function (tmp, item, index) {
//tmp 上次结果,item当前数,index次数1开始
console.log(tmp, item, index)
//1 3 1
//4 5 2
//9 7 3
return tmp + item
})
console.log(result) //16
// 求平均值
var arr = [1, 3, 5, 7]
var result = arr.reduce(function (tmp, item, index) {
if (index != arr.length - 1) { // 不是最后一次
return tmp + item
} else {
return (tmp + item)/arr.length
}
})
console.log(result) //4
let arr = [12, 4, 8, 9]
let result = arr.filter(function (item) {
return item % 3 === 0
})
console.log(result)//[12,9]
let result = arr.filter(item => item % 3 === 0)//简写
console.log(result)//[12,9]
let arr = [12, 4, 8, 9]
let result = arr.every(item => item % 3 === 0)//简写
console.log(result)//false
let arr = [12, 4, 8, 9]
let result = arr.some(item => item % 3 === 0)//简写
console.log(result)//true
let arr = [12, 4, 8, 9]
let result = arr.forEach(item => console.log(item))
//12
//4
//8
//9
原文:https://www.cnblogs.com/jiajia-hjj/p/15156230.html