在最近的采访中,面试官问道,你能用javascript为push()方法编写polyfill吗?
任何人都知道该怎么做。
发布于 2015-07-21 16:30:18
push()在array的末尾添加一个或多个元素,并返回数组的新length。您可以使用数组的length属性在其末尾添加元素。
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;
};
}发布于 2018-03-03 15:04:44
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
复制相似问题