常见的数组迭代方法有很多种,比如 some
, filter
, map
等等,底层也都可以用for
来实现,我们来康一康。
some
const some = (arr, fn) => {
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i, arr)) {
return true
}
}
return false
}
every
const every = (arr, fn) => {
let count = 0
const len = arr.length
for (let i = 0; i < len; i++) {
if (fn(arr[i], i, arr)) {
count++
}
}
return count === len
}
filter
const filter = (arr, fn) => {
const res = []
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i, arr)) {
res.push(arr[i])
}
}
return res
}
find
const find = (arr, fn) => {
for (let i = 0; i < arr.length; i++) {
if (fn(arr[i], i, arr)) {
return arr[i]
}
}
}
map
const map = (arr, fn) => {
const res = []
for (let i = 0; i < arr.length; i++) {
res.push(fn(arr[i]))
}
return res
}
持续更新中...