假设我有一个包含数字19的变量。我想用以下数字从中创建一个数组
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
这在javascript中怎么可能?
答案 0 :(得分:1)
类似的东西:
var number = 19;
var arr = [];
for ( i = 0; i <= number ; i++ ) {
arr.push(i < 10 ? ("0" + i.toString()) : i.toString());
}
答案 1 :(得分:1)
可替换地:
var mynumber = 19,
myarr = String(Array(mynumber+1))
.split(',')
.map(function(el,i){return i<10 ? '0'+i : ''+i;});
对于zeropadding,您可能需要使用:
function padLeft(nr,base,chr){
base = base || 10;
chr = chr || '0';
var len = (String(base).length - String(nr).length)+1;
return len > 0? Array(len).join(chr)+nr : nr;
}
// usage
padLeft(1); //=> '01'
padLeft(1,100); //=> '001'
padLeft(1,10000,'-'); //=> '----1'
答案 2 :(得分:1)
使用此示例终于解决了我自己的@@ iterator函数接口问题; 非常感谢
var myArray = [];
function getInterval (start, step, end, ommit){
for (start; start <= end; start += step) {
myArray.push( start < 10 ? ("" + start.toString()) : start.toString());
}
}
getInterval(2, 2, 20, 20);
myArray; // __proto__: Array
// (10) ["2", "4", "6", "8", "10", "12", "14", "16", "18", "20"]
myArray[4]; // "10"
答案 3 :(得分:0)
基本上你想要填0并且这里的答案不足以在数字改变时进行缩放。可能更好的解决方案是
function padZero(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}