There is a program that adds values to the beginning of the array.
I want to limit the number to 10, but I don't know how to do it.
What should I do?
a=[1]
a.unshift(2)//[2,1]
...
a.unshift(10)// [10,9,8,7,6,5,4,3,2,1]
a.unshift(11)//[11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
I wish I could take out 10 arrays immediately after unshift()
and self-replace them...
How about using splice
below?
function addLimited(array,value,limit){
array.unshift(value);
array.splice(limit);
}
var array=[];
addLimited(array,1,10);
addLimited (array, 2, 10);
addLimited (array, 3, 10);
addLimited (array, 4, 10);
addLimited (array, 5, 10);
addLimited (array, 6, 10);
addLimited (array, 7, 10);
addLimited (array, 8, 10);
addLimited (array, 9, 10);
addLimited (array, 10, 10);
addLimited (array, 11, 10);
console.log(array);//[11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
It's a little aggressive, but you can also do it by rewriting the unshift.
// Create tenAry object with extended array
variantAry={};
tenAry.__proto__=[];
tenAry._unshift = tenAry.unshift
tenAry.unshift=function(v){
This._unshift(v);
This.splice(10);
}
// unshift 20 times
for(vari=0;i<20;i++){
tenAry.unshift(i);
}
console.log(tenAry);//-> [19, 18, 17, 16, 15, 14, 13, 12, 11, 10]
newArray()
If you want to implement it like this, you can do the following:
//Create something like a TenArray class
function TenArray(){}
TenArray.prototype.__proto__=[ ]
TenArray.prototype.unshift=function(v){
This.__proto__.__proto__.unshift.call(this,v);
This.splice(10);
};
// Create a regular array
variable = new Array();
// Unshift creates an array with a maximum prime limit of 10
vartenAry = new TenArray();
a. Change the length to the number you want to limit.
vara=[1,2,3,4,5,6,7,8,9,10,11];
a. length = 10; // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
a.unshift(12); // [12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a. length = 10; // [12, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
vara = [ ];
a. length = 10; // [undefined x 10]
© 2024 OneMinuteCode. All rights reserved.