在最近的采访中,采访者要求你可以写填充工具push()
在JavaScript方法。
有人知道怎么做吗 。?
在最近的采访中,采访者要求你可以写填充工具push()
在JavaScript方法。
有人知道怎么做吗 。?
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;
};
}
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; }; }