filter和map的实现

13次阅读

共计 1551 个字符,预计需要花费 4 分钟才能阅读完成。

1.filter 的用法

菜鸟教程:

filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意:filter() 不会对空数组进行检测。
注意:filter() 不会改变原始数组。

filter 方法会将数组中所有符合条件的元素组成一个新数组,并将新数组作为返回值。判断条件是由回调函数的返回值决定的。另外,filter 具有第二个参数,用于绑定回调函数中的 this。

    const arr = [1, 2, 3]
    console.log(arr.filter(i => i > 1));//[2,3]

2.filter 的实现

    Array.prototype.myFilter = function (cb, thisValue) {if (typeof cb !== 'function') {throw new Error('第一个参数应当为函数')
            }
            // 声明 res 作为返回值
            const res = [];
            //this 不是空数组时,进入,this 是空数组是,直接返回 res
            if (this.length) {for (let i = 0; i < this.length; i++) {
                // 遍历 this,如果回调函数返回值为真,将该项添加到 res 中,否则不添加,以此实现过滤功能
                    cb.call(thisValue, this[i], i, this) ? res.push(this[i]) : null;
                }
            }
            return res
        }

3.map 的用法

菜鸟教程:

map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意:map() 不会对空数组进行检测。返回空数组
注意:map() 不会改变原始数组。

map 返回一个长度和原数组相同的新数组,回调函数中返回值将会依次作为新数组中的元素。和 filter 相同,map 同样具有第二个参数,用于给回调函数绑定 this。
map 使用十分广泛,比如将购物车中的数据存储在本地时,由于商品的全部信息很多,我们更希望只存储必要的信息。

    
    const products = [
            {
                id: 1,
                name: 'xxx',
                price: 'xxx',
                img: 'xxx',
                count: 2

            },
            {
                id: 2,
                name: 'xxx',
                price: 'xxx',
                img: 'xxx',
                count: 2

            },
            {
                id: 3,
                name: 'xxx',
                price: 'xxx',
                img: 'xxx',
                count: 2

            },
            {
                id: 4,
                name: 'xxx',
                price: 'xxx',
                img: 'xxx',
                count: 2
            },
        ]
        // 将商品的 id 和数量存储到本地 回调函数的返回值{id: item.id, count: item.count} 将作为新数组中的元素
        const mapProducts = products.map(item => ({ id: item.id, count: item.count}))
        console.log(mapProducts);//[{id:1,count:2}...]
        localStorage.setItem('products', JSON.stringify(mapProducts))

map 的实现

Array.prototype.myMap = function (cb, thisValue) {if (typeof cb !== 'function') {throw new Error('第一个参数应当为函数')
            }
            const res = [];
            if (this.length) {for (let i = 0; i < this.length; i++) {
                // 遍历数组时,将每次回调函数的返回值添加到 res 中
                    res.push(cb.call(thisValue, this[i], i, this))
                }
            }
            return res
        }
仅为个人理解,如有错谬,欢迎指正。
如果对您有所帮助,请您点个赞吧!
正文完
 0