every -- 判断数组中的每一项是否都满足 回调函数 的验证
// 仿写:
Array.prototype._every = function (callback) {
if (this.length == 0) throw Error("every() error: 数组不能为空!")
for (let i = 0; i < this.length; i++) {
const value = this[i]
if (callback(value, i, this) == false) return false
}
return true
}
// 使用:
const nums = [1, 30, 39, 29, 5, 13]
var result = nums._every(function (item, index, array) {
return item > 30
})
console.log(result ? "都大于30" : "非都大于30")
some
判断数组中是否存在满足 回调函数 验证的项目
// 仿写:
Array.prototype._some = function (callback) {
if (this.length == 0) throw Error("some() error: 数组不能为空!")
for (let i = 0; i < this.length; i++) {
const value = this[i]
if (callback(value, i, this) == true) return true
}
return false
}
// 使用:
var nums = [1, 30, 26, 29, 5, 13]
var result = nums._some(function (item, index, array) {
return item > 30
})
console.log(result ? "有大于30的" : "不存在大于30的")
forEach
遍历数组中的每一项, 通过 回调函数 进行处理
// 仿写
Array.prototype._forEach = function (callback) {
for (let i = 0; i < this.length; i++) {
const value = this[i]
callback(value, i, this)
}
}
// 使用
var nums = [1, 30, 26, 29, 5, 13]
nums._forEach(function (item, index, array) {
console.log(item)
})
map
返回一个新的数组, 数组中由回调函数的返回值组成
// 仿写:
Array.prototype._map = function (callback) {
let arr = []
for (let i = 0; i < this.length; i++) {
const value = this[i]
arr.push(callback(value))
}
return arr
}
// 使用:
var nums = [1, 30, 26, 29, 5, 13]
var new_nums = nums._map(function (item, index, array) {
return item * 2
})
console.log(new_nums)
// [2, 60, 52, 58, 10, 26]
filter
返回一个新的数组, 其中的值 都是经过 回调函数 验证为真的
// 仿写:
Array.prototype._filter = function (callback) {
let arr = []
for (let i = 0; i < this.length; i++) {
const value = this[i]
if (callback(value, i, this) == true) {
arr.push(value)
}
}
return arr
}
// 使用:
var nums = [1, 30, 26, 29, 5, 13]
var new_nums = nums._filter(function (item, index, array) {
return item > 25
})
console.log(new_nums)
// [30,26,29]
reduce
把数组的内容进行归纳, 最后合并为一个值作为结果. 具体归纳规则 要看 回调函数
// 仿写:
Array.prototype._reduce = function (callback) {
if (this.length == 0) throw Error("reduce: 数组不能为空")
// 默认 总和的初始值为 数组中的第一个项目
var sum = this[0]
// 如果传递了参数2, 则总和的初始值为参数2
if (arguments.length == 2) sum = arguments[1]
// 起始序号 根据是否传递了参数2, 将会有所差别
// 未传递参数2, 则从序号1 开始
// 传递了参数2, 则从序号0 开始
for (let i = arguments.length == 2 ? 0 : 1; i < this.length; i++) {
const value = this[i]
sum = callback(sum, value, i, this)
}
return sum
}
// 使用:
var nums = [1, 2, 3, 4]
var result = nums._reduce(function (sum, item, index, array) {
return sum + item
}, 0)
console.log(result) //10