gpt4 book ai didi

javascript - 什么是可以用来递增字母的方法?

转载 作者:IT王子 更新时间:2023-10-29 02:45:07 25 4
gpt4 key购买 nike

有人知道提供递增字母方法的 Javascript 库(例如下划线、jQuery、MooTools 等)吗?

我希望能够做这样的事情:

"a"++; // would return "b"

最佳答案

简单、直接的解决方案

function nextChar(c) {
return String.fromCharCode(c.charCodeAt(0) + 1);
}
nextChar('a');

正如其他人所指出的,缺点是它可能无法按预期处理字母“z”之类的情况。但这取决于你想从中得到什么。上面的解决方案将为“z”之后的字符返回“{”,这是 ASCII 中“z”之后的字符,因此它可能是您要查找的结果,具体取决于您的用例。


独特的字符串生成器

(更新于 2019/05/09)

由于这个答案受到了如此广泛的关注,我决定将其扩展到原始问题的范围之外,以潜在地帮助那些在 Google 上遇到这个问题的人。

我发现我经常想要的是在特定字符集中生成连续的、唯一的字符串(例如只使用字母)的东西,所以我更新了这个答案以包含一个可以在此处执行此操作的类:

class StringIdGenerator {
constructor(chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
this._chars = chars;
this._nextId = [0];
}

next() {
const r = [];
for (const char of this._nextId) {
r.unshift(this._chars[char]);
}
this._increment();
return r.join('');
}

_increment() {
for (let i = 0; i < this._nextId.length; i++) {
const val = ++this._nextId[i];
if (val >= this._chars.length) {
this._nextId[i] = 0;
} else {
return;
}
}
this._nextId.push(0);
}

*[Symbol.iterator]() {
while (true) {
yield this.next();
}
}
}

用法:

const ids = new StringIdGenerator();

ids.next(); // 'a'
ids.next(); // 'b'
ids.next(); // 'c'

// ...
ids.next(); // 'z'
ids.next(); // 'A'
ids.next(); // 'B'

// ...
ids.next(); // 'Z'
ids.next(); // 'aa'
ids.next(); // 'ab'
ids.next(); // 'ac'

关于javascript - 什么是可以用来递增字母的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12504042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com