我是 JavaScript 新手。这是我的任务
我想生成一个以“A”开头且数字递增的序列号。 示例:A000001、A000002、...、A000010 等。 我想根据我作为输入给出的当前年份生成此序列号。 例子 : 如果当前年份是 2020 年,则 A000001、A000002、...、A000010 等等 如果当前年份是 2021 年,则 B000001、B000002、...、B000010 等等 如果当前年份是 2046,那么它应该类似于 AA000001、AA000002、...、AA000010 等等。因为有26个字母,所以应该从AA开始。 2047 - AB、2048 - AC 等也是如此。
function colName(n) {
var ordA = 'A'.charCodeAt(0);
var ordZ = 'Z'.charCodeAt(0);
var len = ordZ - ordA + 1;
var year = 2020;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
这里我有一个代码,它将以 A、B、C、....Z、AA 的方式生成字母表。但是当我调用函数 colName(n) 时,'n' 的值应该从 0 给出,从 'A' 开始。我想给出当前年份的值。如果我给 n 值 2020,那么它应该显示“A”。
我被困在这里,不知道如何执行此操作以及如何添加递增数字。 Here I am giving an image of my concept
谢谢。
最佳答案
您需要在 2020 年减去 n,使其成为起点(将其视为偏移量)。 另外,2027 年将是 H 而不是 AA,因为 2020=A,并且从那里开始的 26 个字符将是 Z。
function colName(n) {
var ordA = 'A'.charCodeAt(0);
var ordZ = 'Z'.charCodeAt(0);
var len = ordZ - ordA + 1;
n -= 2020;
var s = "";
while(n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
document.write(colName(2020));
关于javascript - 从特定输入增加字母表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60223480/