wen*_*ndy 1 javascript php excel for-loop
基本上我想做的是创建格式类似于 Excel 列名称的字符列表。
例如:a,b,c,d,.....,z,aa,ab,ac,......,yz
在 php 中,您可以使用以下代码循环它:
for($char = "A"; $char <= "Z"; $char++)
{
echo $char . "\n";
}
Run Code Online (Sandbox Code Playgroud)
但是当我在 javascript 中尝试它时:
var i3;
var text3 = "";
for(i3 = "A"; i3 <= "Z"; i3++)
{
text3 += i3 + ", ";
}
document.getElementById("pId").innerHTML = text3;
Run Code Online (Sandbox Code Playgroud)
这对我不起作用。我的代码中有一些错误吗?或者 PHP 逻辑在 JS 中不起作用?如果你知道怎么制作请告诉我,谢谢。
短就是美!
var nextChar = c=>c?String.fromCharCode(c.charCodeAt(0)+1):'A';
var nextCol = s=>s.replace(/([^Z]?)(Z*)$/, (_,a,z)=>nextChar(a) + z.replace(/Z/g,'A'));
//test:
nextCol(''); //A
nextCol('A'); //B
nextCol('Z'); //AA
nextCol('AA'); //AB
nextCol('XYZ'); //XZA
nextCol('ZZZZ'); //AAAAA
//output: A,B,C,...,ZZ
for(var i=0, s=''; i<702; i++){
s = nextCol(s);
console.log(s);
}
//output: A,B,C,...,ZZZZ
for(var i=0, s=''; i<475254; i++){
s = nextCol(s);
console.log(s);
}
Run Code Online (Sandbox Code Playgroud)