首页 > Web开发 > 详细

js原生方法reduce实现

时间:2020-01-19 12:03:45      阅读:268      评论:0      收藏:0      [点我收藏+]
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="author" content="杨欣">
    <title>reduce</title>
</head>

<body>

    <script>
        Array.prototype.my_reduce = function (callback, initialValue) {
            if (!Array.isArray(this) || !this.length || typeof callback !== 'function') {
                return []
            } else {
                // 判断是否有初始值
                let hasInitialValue = initialValue !== undefined;
                let value = hasInitialValue ? initialValue : tihs[0];
                for (let index = hasInitialValue ? 0 : 1; index < this.length; index++) {
                    const element = this[index];
                    value = callback(value, element, index, this)
                }
                return value
            }
        }

        let arr = [1, 2, 3, 4, 5]
        let res = arr.my_reduce((pre, cur, i, arr) => {
            console.log(pre, cur, i, arr)
            return pre + cur
        }, 10)
        console.log(res)//25
    </script>
</body>

</html>

js原生方法reduce实现

原文:https://www.cnblogs.com/samsara-yx/p/12212936.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!