JS: Apply Array Method to Array-Like Object
to apply Array methods to Array-Like Object, do:
Reflect.apply(arrayMethod, ArrayLikeObj, [arrayMethodArgs]);
γsee Reflect.applyγ
// using a array method Array.prototype.map directly on array-like object const arLike = { 0: "a", 1: "b", 2: "c", length: 3 }; function ff(x) { return x + "z"; } const xResult = Reflect.apply(Array.prototype.map, arLike, [ff]); // result is a array console.log(Array.isArray(xResult)); xResult; // [ "az", "bz", "cz" ]
or do:
arrayMethod.call(ArrayLikeObj, arrayMethodArgs)
γsee Function.prototype.callγ
// using a array method Array.prototype.map directly on array-like object const arLike = { 0: "a", 1: "b", 2: "c", length: 3 }; function ff(x) { return x + "z"; } const xResult = Array.prototype.map.call(arLike, ff); // result is a array console.log(Array.isArray(xResult));