It should be easy, but there are a few special points.
The callback function allows you to modify the array in question. Any items that it adds or removes are not visited. Therefore, it seems to us that we should use something like Object.keys to determine which elements should be visited.
In addition, the result is defined as a new array, "created as if" by an array constructor occupying the length of the old array, so we could also use this constructor to create it.
Here the implementation takes these things into account, but some other subtleties are probably missing:
function map(callbackfn, thisArg) { var keys = Object.keys(this), result = new Array(this.length); keys.forEach(function(key) { if (key >= 0 && this.hasOwnProperty(key)) { result[key] = callbackfn.call(thisArg, this[key], key, this); } }, this); return result; }
I assume that Object.keys returns the keys of the array in numerical order, which, in my opinion, is determined by the implementation. If it is not, you can sort them.
source share