In recent interview, interviewer has asked can you write polyfill for push() method in javascript.
any one know how to do this .?
push() adds one or more elements at the end of array and returns new length of array. You can use array's length property to add element at the end of it.
if (!Array.prototype.push) {
// Check if not already supported, then only add. No need to check this when you want to Override the method
// Add method to prototype of array, so that can be directly called on array
Array.prototype.push = function() {
// Use loop for multiple/any no. of elements
for (var i = 0; i < arguments.length; i++) {
this[this.length] = arguments[i];
}
// Return new length of the array
return this.length;
};
}
this.length to make Array.prototype.push generic. So somewhere add this.length = Number(this.length) || 0; and this.length += 1.this.length += 1 is not needed, as you're adding new elements in array, length will be automatically incremented by one, for each additionArray.prototype.push.call on, e.g. {length: 0}.if (!Array.prototype.push) {
Array.prototype.push = function () {
for (var i = 0, len = arguments.length; i < len; i++) {
this[this.length] = arguments[i];
if (Object.prototype.toString.call(this).slice(8, -1).toLowerCase() === 'object') {
this.length += 1;
}
}
return this.length;
};
}