Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

手写实现Array.prototype.map/filter/reduce #18

Open
HelenHai opened this issue Oct 10, 2021 · 0 comments
Open

手写实现Array.prototype.map/filter/reduce #18

HelenHai opened this issue Oct 10, 2021 · 0 comments

Comments

@HelenHai
Copy link
Owner

Array.ptototype.map

Array.prototype.map1 = function(fn) {
    let arr = []

    for(let i=0; i<this.length; i++) {
        arr.push(fn(this[i]))
    }
    return arr
}

Array.ptototype.filter

Array.prototype.filter1 = function(fn) {
    let arr = []

    for(let i=0; i<this.length; i++) {
        fn(this[i]) && arr.push(this[i])
    }
    return arr
}

Array.ptototype.reduce

Array.prototype.reduce1 = function(fn, initial) {
    for(let i=0; i<this.length; i++) {
        initial = fn(initial, this[i], i, this)
    }
    return initial
}

references

  1. for 循环不是目的,map 映射更有意义!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant