我这里有一个代码,可以获取 0 到 45 之间的 6 个非重复数字,到目前为止它可以工作,除了我想要一个循环来更改我的数字,这样如果数字低于 10,它会在前面添加一个 0,这样每个数字的格式都是“xx”,例如“07”、“25”、“00”
我试图为我的代码创建一个 for 循环,但每次尝试时它都会中断。我试图用这个 for 循环来减少代码的长度。
我的代码现在可以工作了,但是我有一个令人讨厌的 6 个 if 语句。
我已经尝试过这个:
var z;
for (z = 1; z < 7; z++) {
if (n[z] < 10) {
n[z] = "0" + n[z];
}
}
这是我的代码:
function randomNo(){
function arrayShuffle () {
var i = this.length, j, temp;
if ( i === 0 ) return false;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
}
Array.prototype.shuffle =arrayShuffle;
var start = 0;
var end = 45;
var numbers = new Array();
for (var i = start; i <= end; i++) {
numbers.push(i);
}
numbers.shuffle();
var n1 = numbers.pop();
var n2 = numbers.pop();
var n3 = numbers.pop();
var n4 = numbers.pop();
var n5 = numbers.pop();
var n6 = numbers.pop();
// Should replace for a for loop, but I cant figure it out
// Replace in html
console.log(n1);
console.log(n2);
console.log(n3);
console.log(n4);
console.log(n5);
console.log(n6);
}
randomNo();
每次我尝试 for 循环时,我的数字都完全停止工作,并且在 HTML 中我只能得到等待查询选择器替换的起始文本。
最佳答案
将数字转换为字符串,然后:
1) 使用字符串的 padStart
方法:
function ex(inp) {
return inp.toString().padStart(2, '0');
}
console.log(ex(1));
console.log(ex(154));
console.log(ex(9));
2)检查字符串的长度,如果小于2,则添加前导0:
function ex(numb) {
return numb.toString().length < 2 ? `0${numb}` : numb;
}
console.log(ex(1));
console.log(ex(154));
console.log(ex(13));
console.log(ex(9));
关于javascript - 如何正确地为我的变量创建 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54008985/