假设我有一个变量,它包含数字 19。我想从中创建一个包含以下数字的数组
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
这在javascript中怎么可能?
假设我有一个变量,它包含数字 19。我想从中创建一个包含以下数字的数组
var positions = [ "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" ];
这在javascript中怎么可能?
就像是 :
var number = 19;
var arr = [];
for ( i = 0; i <= number ; i++ ) {
arr.push(i < 10 ? ("0" + i.toString()) : i.toString());
}
演示:http: //jsfiddle.net/Kfnnr/1/
或者:
var mynumber = 19,
myarr = String(Array(mynumber+1))
.split(',')
.map(function(el,i){return i<10 ? '0'+i : ''+i;});
对于零填充,您可能需要使用:
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'
2019 年更新:在 es20xxString.prototype
中包含一个本地padStart
方法:
"1".padStart(2, "0"); //=> "01"
// ^ max length
// ^ fill string (or space if omitted)
本质上你想填充 0,当数字改变时,这里的答案是不够的和扩展的。可能更好的解决方案是
function padZero(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
使用这个例子终于解决了我自己的@@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"