I want to create an array in javascript to have 20 elements with a starting index of 15, assign every element with a value of 00000. What is the most efficient way, and can it be done without looping through the index?
TIA.
Array indexes in javascript are always in the interval [0, num_elements)
. If you do not want this, you need to use an object. Then you have arbitraty indexes but no fixed order.
Without loop you can only use instant initialization:
var arr = [null, null, null, ... 15 times ...., '000000', '000000', '000000', '000000', '000000'];
But probably it's better to use loop :)
It's better to use an object
, if you want to use an offset:
var iOffset = 15;
var iCount = 20;
var oValues = {};
for (var i = iOffset ; i < iOffset + iCount; i++) {
oValues[i] = 0;
}
You can't have an array starting with an index of 15. The index of an array always start with index 0, as is demonstrated with:
var a = [];
a[15] = '000';
alert(a.length); //=> 16
You could use a recursive function to create an array of 20 elements, something like:
function arr(len){
return len ? arr(len-1).concat('0000') : [];
}
var myArr = arr(20);
Or create an array of small objects, containing your custom index:
function arr(len){
return len ? arr(len-1).concat({index:len+14,value:'0000'}) : [];
}
var myArr = arr(20);
alert(myArr[0].index); //=> 15
Alternatively, using a loop, you can do something like:
var nwArr = function(len,start){
var l = len+start, a = Array(l);
while ((l-=1)>=start){ a[l] = '0000'; }
return a;
}(20,15);
alert(nwArr[15]); //=> '0000'
alert(nwArr[0]); //=> undefined
For the specific case where each item in the array is a string, you can do it without a loop with the new Array(length)
constructor and a sneaky join
:
new Array(15).concat(('000000'+new Array(20).join(',000000')).split(','))
Unlikely to be faster than the loop though... certainly less clear. I'd also question whether an Array with missing properties 0–14 is something it's generally sensible to have.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.