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

实现一个原生的数组Map #3

Open
lynhao opened this issue Sep 12, 2020 · 0 comments
Open

实现一个原生的数组Map #3

lynhao opened this issue Sep 12, 2020 · 0 comments

Comments

@lynhao
Copy link
Owner

lynhao commented Sep 12, 2020

屏幕快照 2020-09-12 18 45 29

Array.prototype._map = function(callbackfn, thisArg) {
    let O = new Object(this);
    if (this === null || this === undefined) {
        throw new TypeError("Cannot read property 'map' of null or undefined");
    }
    if (Object.prototype.toString.call(O) !== "[object Array]") {
        throw new TypeError("this is not a Array!")
    }
    let len = O.length >>> 0; // 向右移动0位, 相当于Math.floor
    if (Object.prototype.toString.call(callbackfn) !== "[object Function]") {
        throw new TypeError(callbackfn + "is not a function!")
    }
    let T = thisArg ? thisArg : undefined
    let A = new Array(len);
    let k = 0;
    while(k < len) {
        if (k in O) {
            let kValue = O[k];
            let mappedValue = callbackfn.call(T, kValue, O);
            A[k] = mappedValue;
        }
        k++;
    }
    return A;
    
}

Test

[2,3,4]._map(r => r * 2) // [4,6,8]

[{b:1},{b:2}]._map(r => {
    return {
        ...r,
        c: r.b
    }
}) 
//[{b:1, c:1},{b:2, c:2}]
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