如何转换1234567890 = ABCDEFGHIJ,例如。360 to CFJ
我知道如何针对单个字符执行此操作:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
Run Code Online (Sandbox Code Playgroud)
但不确定如何一次处理多个/一组数字:例如 230 to BCJ
在fromCharCode接受一个列表参数作为参数。
String.fromCharCode(72, 69, 76, 76, 79); 例如将打印“你好”。
不过,您的示例数据无效。例如,字母“A”是 65。您需要创建一个逗号分隔的参数,并将其输入到函数中。如果您不将其作为逗号分隔的 arg 提供,您将尝试解析很可能会失败的单个键代码。
这将工作:
function convert(num) {
return num
.toString() // convert number to string
.split('') // convert string to array of characters
.map(Number) // parse characters as numbers
.map(n => (n || 10) + 64) // convert to char code, correcting for J
.map(c => String.fromCharCode(c)) // convert char codes to strings
.join(''); // join values together
}
console.log(convert(360));
console.log(convert(230));Run Code Online (Sandbox Code Playgroud)
只是为了好玩,这是使用Ramda的版本:
const digitStrToChar = R.pipe(
Number, // convert digit to number
R.or(R.__, 10), // correct for J
R.add(64), // add 64
R.unary(String.fromCharCode) // convert char code to letter
);
const convert = R.pipe(
R.toString, // convert number to string
R.split(''), // split digits into array
R.map(digitStrToChar), // convert digit strings to letters
R.join('') // combine letters
);
console.log(convert(360));
console.log(convert(230));Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2600 次 |
| 最近记录: |