有谁知道 Javascript 库(例如 underscore、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)
由于这个答案已经得到了如此多的关注,我决定将其扩展到原始问题的范围之外,以潜在地帮助那些在谷歌上遇到这个问题的人。
我发现我经常想要的是能够在特定字符集中生成连续的、唯一的字符串(例如仅使用字母),因此我更新了这个答案以包含一个可以在此处执行此操作的类:
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();
}
}
}
Usage:
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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)