我错误的例子:
var prefix = '1234';
for (var x = 4; x<= 10; x++)
if (prefix.length !== x) {
prefix.concat('0')
}
我试图得到:['1234', '12340', '123400', '1234000', '1234000', '123400000', '1234000000']
你需要重新赋值给变量;concat
不修改字符串
const res = [];
var prefix = '1234';
for (var x = 4; x <= 10; x++) {
res.push(prefix);
prefix = prefix.concat('0');
}
console.log(res);
你也可以使用Array.from
和String#repeat
。
const prefix = '1234';
const res = Array.from({length: 7}, (_,i)=>prefix+'0'.repeat(i));
console.log(res);
let array = [];
let prefix = "1234";
for(let n=0; n<7; n++){
let new_value = prefix;
for(let i=0;i<n;i++){
new_value += "0";
}
array.push(new_value);
}
console.log(array);
供您参考,您可以使用while循环来代替for循环,从而使您的代码更简洁:
var prefix = '1234';
var array = [];
while (prefix.length <= 10) {
array.push(prefix);
prefix += '0';
}
console.log(array);