function filter(array, predicate) {
let index = -1
let resIndex = 0
const length = array == null ? 0 : array.length
const result = []
while (++index < length) {
const value = array[index]
if (predicate(value, index, array)) {
result[resIndex++] = value
}
}
return result
}
export default filter
解析:
当后面的函数返回ture时,才会将该项放进新数组中,如下:
if (predicate(value, index, array)) {// !!!这个重要
result[resIndex++] = value
if (predicate(value, index, array)) {// !!!这个重要
result[resIndex++] = value
}