Home > Software engineering >  What are the differences between the two ways to implement Array.prototype.map
What are the differences between the two ways to implement Array.prototype.map

Time:09-08

Array.prototype.myMap = function (cb, thisArg) {
    const newArr = []
    for (let i = 0; i < this.length; i  ) {
        if (i in this) {
            newArr[i] = cb.call(thisArg, this[i], i, this)
        }
    }
    return newArr
}
Array.prototype.myMap = function (cb, thisArg) {
    const newArr = []
    const len = this.length
    for (let i = 0; i < len; i  ) {
        if (i in this) {
            newArr[i] = cb.call(thisArg, this[i], i, this)
        }
    }
    return newArr
}

whth the "i < this.length" I don't know why isn't pass any test case ,It's show infinite always

CodePudding user response:

These will be different if the callback function modifies the length of the array being iterated over. For instance:

[1, 2, 3].myMap((el, index, array) => {
    array.push(0);
    return el   1;
});

The second version will never end because this.length keeps increasing as the loop continues. But the first version just processes the original 3 elements of the array.

  • Related