let output ="I am a string"
const app=output.split("")
console.log(app)
//输出(13)"我,";","a","m",";","a",";","s","t","r","我,"n","g")
则需要按字母顺序将每个字母改为下一个
这意味着
"j",","b","n",","b",","t","u","s","j","o","h"
之后的字符串必须写成;"jbnbtusjoh">
的意见吗?
让我们一步一步来:
// first the string
let out = "I am a string"
// convert to array
let arOut = out.split("") // gives ["I"," ", "a", "m", " ", "a"....]
// now lets get cracking :
let mapped = arOut.map(element => element == ' ' ? element : String.fromCharCode(element.charCodeAt(0)+1))
// this get char code of element and then adds one and gets equivalent char ignores space
let newOut = mapped.join("") // we have our result
console.log(newOut)
分割后,映射字符数组,将每个字符转换为代码(如果不是空格),添加一个,并将代码转换回char:
const output = 'I am a string'
const result = output.split('')
.map(c => c === ' '
? c // ignore spaces
: String.fromCharCode(c.charCodeAt(0) + 1) // convert char to code, add one, and convert back to char
)
.join('') // if you need a string
console.log(result)
您也可以使用Array.from()
直接将字符串转换为转换后的字符数组:
const output = 'I am a string'
const result = Array.from(
output,
c => c === ' ' ? c : String.fromCharCode(c.charCodeAt(0) + 1)
).join('')
console.log(result)
为什么不将每个字符转换为ASCII,然后简单地增加数字?