js原生方法filter實現


<!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>filter</title>
</head>

<body>

    <script>
        Array.prototype.my_filter = function (callback) {
            if (!Array.isArray(this) || !this.length || typeof callback !== 'function') {
                return []
            } else {
                let result = [];
                for (let index = 0; index < this.length; index++) {
                    const element = this[index];
                    if (callback(element, index, this)) {
                        result.push(element)
                    }
                }
                return result
            }
        }

        let arr = [1, 2, 3, 4, 5]
        let res = arr.my_filter((ele, i) => {
            return ele % 2 === 0
        })
        console.log(res)//[2,4]
    </script>
</body>

</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM