ES5 every/some/reduce/reduceRight的使用与重写

被作为实参传入另一函数,并在该外部函数内被调用,用以来完成某些任务的函数,称为回调函数。

break、return用于终止循环的区别:

  • return只能用在函数体内(单独一个for循环里直接用return会报错)
  • 对于多层循环:return直接终止,而break只是跳出所在层的循环

every

  • return后的表达式为条件
  • 如有一不满足条件就停止遍历
  • 返回值是布尔值
  • 可以改变this指向
  • 重写
function myEvery(callback) {
    var arr = this,
        obj = arguments[1] || window;
    for (var i = 0; i < arr.length; i++) {
        console.log(i)
        if (!callback.apply(obj, [arr[i], i, arr])) {
            return false
        }
    }
    return true
}
Array.prototype.myEvery = myEvery
var arr = [1, 2, 3, 4, 5]
console.log(arr.myEvery((ele) => {
    return ele > 1
}))

some

  • 只要有一个条件满足就停止遍历
  • 返回值是布尔值
  • 可以改变this指向
function mySome(callback) {
    var arr = this,
        obj = arguments[1] || window;
    for (var i = 0; i < arr.length; i++) {
        console.log(i)
        if (callback.apply(obj, [arr[i], i, arr])) {
            return true
        }
    }
    return false
}
Array.prototype.mySome = mySome
var arr = [1, 2, 3, 4, 5]
console.log(arr.mySome((ele) => {
    return ele > 6
}))

reduce 归纳函数(重要)

  • 参数1:回调函数4参数:prev | ele, index, arr
  • 参数2:initVal(必传)
  • prev的初始值是initVal给的
  • 每次循环可以操作prev
  • 类似filter,filter是过滤,返回(return)布尔值,就往容器里放
  • reduce是归纳,符合条件(if语句)就往容器里放
  • reduce返回新数组nArr即回调函数内return的内容(prev)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 和map、forEach的区别,有了一个初始值initVal
// 将url参数转为数组形式
var qs = 'v=1&_v=j90&aip=1&a=152878233&t=pageview&_s=1&dl=https%3A%2F%2Fdeveloper.mozilla.org%2Fzh-CN%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fstringify&ul=zh-cn&de=UTF-8&dt=JSON.stringify()%20-%20JavaScript%20%7C%20MDN&sd=24-bit&sr=1536x864&vp=1519x182&je=0&_u=QACAAAABAAAAAC~&jid=1406847847&gjid=1261334307&cid=1705225672.1581390240&tid=UA-36116321-5&_gid=1728790607.1622245970&_r=1&_slc=1&z=575736183'
var arr = qs.split('&')
var nArr = arr.reduce(function (prev, ele) {
    qArr = ele.split('=')
    prev[qArr[0]] = qArr[1]
    return prev
}, {})
console.log(nArr)
  • 重写
function myReduce(callback, initVal) {
    var arr = this;
    var obj = arguments[2] || window
    var nRes
    var prev
    for (var i = 0; i < arr.length; i++) {
        prev = i === 0 ? initVal : nRes
        nRes = callback.apply(obj, [prev, arr[i]])
    }
    return nRes
}
Array.prototype.myReduce = myReduce
var qs = 'v=1&_v=j90&aip=1&a=152878233&t=pageview&_s=1&dl=https%3A%2F%2Fdeveloper.mozilla.org%2Fzh-CN%2Fdocs%2FWeb%2FJavaScript%2FReference%2FGlobal_Objects%2FJSON%2Fstringify&ul=zh-cn&de=UTF-8&dt=JSON.stringify()%20-%20JavaScript%20%7C%20MDN&sd=24-bit&sr=1536x864&vp=1519x182&je=0&_u=QACAAAABAAAAAC~&jid=1406847847&gjid=1261334307&cid=1705225672.1581390240&tid=UA-36116321-5&_gid=1728790607.1622245970&_r=1&_slc=1&z=575736183'
var arr = qs.split('&')
var nRes = arr.myReduce(function (prev, ele) {
    qArr = ele.split('=')
    prev[qArr[0]] = qArr[1]
    console.log(this)
    return prev
}, {}, { name: 'this' })
console.log(nRes)

在这里插入图片描述

reduceRight

  • 从最后一个开始倒着遍历,和reduce的顺序相反
function myReduce(callback, initVal) {
    var arr = this;
    var obj = arguments[2] || window
    var nRes
    var prev
    for (var i = 0; i < arr.length; i++) {
        prev = i === 0 ? initVal : nRes
        nRes = callback.apply(obj, [prev, arr[i], i, arr])
    }
    return nRes
}
Array.prototype.myReduce = myReduce
Array.prototype.myReduceRight = function (callback, initVal) {
    var arr = this;
    var obj = arguments[2] || window
    for (var i = arr.length - 1; i >= 0; i--) {
        initVal = callback.apply(obj, [initVal, arr[i], i, arr])
    }
    return initVal
}
var arr = [1, 2, 3, 4, 5]
var nRes1 = arr.myReduce(function (prev, ele, index, arr) {
    prev.push(index + ':' + ele)
    return prev
}, [])
console.log(nRes1)
var nRes2 = arr.myReduceRight(function (prev, ele, index, arr) {
    prev.push(index + ':' + ele)
    return prev
}, [])
console.log(nRes2)

在这里插入图片描述

练习

  • 实现模糊搜索
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" id="J_searchInput" placeholder="请输入小说">
    <ul class="J_list">
        <span>暂无数据</span>
    </ul>
    <div id="J_data" style="display: none;">
        [{"id":1,"name":"飞狐外传","chargeFlag":0},{"id":2,"name":"雪山飞狐","chargeFlag":0},{"id":3,"name":"连城诀","chargeFlag":0},{"id":4,"name":"天龙八部","chargeFlag":1},{"id":5,"name":"射雕英雄传","chargeFlag":1},{"id":6,"name":"白马啸西风","chargeFlag":0},{"id":7,"name":"鹿鼎记","chargeFlag":1}]
    </div>
    <script type="text/html" id="J_tpl">
        <li>{{name}}</li>
    </script>
    <script>
        ; (function (document) {
            var oInput = document.getElementById('J_searchInput')
            var data = JSON.parse(document.getElementById('J_data').innerHTML)
            var tpl = document.getElementById('J_tpl').innerHTML;
            var list = document.getElementsByClassName('J_list')[0]
            var emptyTpl = list.innerHTML
            var init = function () {
                bindEvent()
            }
            function bindEvent() {
                oInput.addEventListener('input', inputBlur, false)
            }
            function inputBlur(e) {
                // console.log(this.value) // 这就可以获取value
                var e = e || window.event;
                var tar = e.target || e.srcElement;
                var tagName = tar.tagName.toLowerCase()
                if (tagName === 'input') {
                    var foundNames = searchByName(tar.value)
                    list.innerHTML = renderList(foundNames)
                }
            }
            function searchByName(key) {
                if (!key) {
                    return []
                }
                return data.reduce(function (prev, ele) {
                    // 模糊搜索
                    var name = ele.name
                    name.includes(key) ? prev.push(ele) : ''
                    return prev
                }, [])
            }
            function renderList(data) {
                if (data.length === 0) {
                    return emptyTpl
                }
                var list = ''
                data.forEach((item) => {
                    list += tpl.replace(/{{(.*?)}}/g, function (node, key) {
                        return {
                            name: item.name
                        }[key]
                    })
                })
                return list
            }
            init()
        })(document)

    </script>
</body>

</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值