问题
In recent interview, interviewer has asked can you write polyfill for push()
method in javascript.
any one know how to do this .?
回答1:
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;
};
}
回答2:
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;
};
}
来源:https://stackoverflow.com/questions/31533963/polyfill-for-push-method-in-javascript