For example, if you set the maximum length of an array to 9, and delete it if it exceeds 9, what should you do?
高洛峰2017-05-19 10:23:23
//重写push方法
Array.prototype.push = function(o,capacity){
var start = this.length;
if(capacity && start>=capacity){
this.pop();
start--;
}
start = Math.max(start,0);
this.splice(start,0,o);
return this;
}
習慣沉默2017-05-19 10:23:23
if(arr.length>9){
arr.length=9;
}
This ensures that the maximum length is 9
世界只因有你2017-05-19 10:23:23
I assume that your application scenario is to automatically detect the length when pushing elements into the array, and delete them after copying 9. Wouldn’t it be very rigid to call the detection method every time you push? I have an idea: rewrite the push method of array