Caesar Cypher Javascript(来自Odin项目)
我仍在学习JS,希望在不复制的情况下做这个练习,但现在我被卡住了…我知道还有很多其他事情需要纠正,但现在…我不知道为什么这个函数不允许空白 **函数获取要编码的字符串和移位因子,然后返回编码的字符串: 凯撒('A',1)//简单地将字母移位1:返回'B' 密码应保留大写: 凯撒('Hey',5)//返回'Mjd; 不应移动标点符号: 凯撒('Hello,World!',5)//返回'Mjqqt,Btwqi!'Caesar Cypher Javascript(来自Odin项目),javascript,Javascript,我仍在学习JS,希望在不复制的情况下做这个练习,但现在我被卡住了…我知道还有很多其他事情需要纠正,但现在…我不知道为什么这个函数不允许空白 **函数获取要编码的字符串和移位因子,然后返回编码的字符串: 凯撒('A',1)//简单地将字母移位1:返回'B' 密码应保留大写: 凯撒('Hey',5)//返回'Mjd; 不应移动标点符号: 凯撒('Hello,World!',5)//返回'Mjqqt,Btwqi!' const caesar = function (word, x) {
const caesar = function (word, x) {
const alpha = "abcdefghijklmnopqrstuvwxyz".split("")
const alphaUp = "abcdefghijklmnopqrstuvwxyz".toUpperCase().split("")
const newString = []
for (const l in word) {
console.log(word[l])
console.log(typeof word[l])
if (word[l] === word[l].toUpperCase()) {
const index2 = alphaUp.findIndex(b => b == word[l])
newString.push(alphaUp[index2 + x])
}
else if (word[l] === " ") {
newString.push(word[l])
}
else if (word[l] === word[l].toLowerCase()) {
const index = alpha.findIndex(a => a == word[l])
newString.push(alpha[index + x])
}
}
console.log(newString.join(""))
}
caesar("Hello world!", 5)
以到达循环中的空格
“
为例,第一个检查是
if(word[l]==word[l].toUpperCase())
在“
上运行.toUppercase()将返回”
,因此您正在运行大写字母的逻辑,并且永远不会到达检查它是否为空格,如果为。将逻辑顺序更改为该顺序将按照您的意愿工作
if (word[l] === " ") {
newString.push(word[l])
}
else if (word[l] === word[l].toUpperCase()) {
const index2 = alphaUp.findIndex(b => b == word[l])
newString.push(alphaUp[index2 + x])
} // rest of the code after
您好,欢迎来到Stack Overflow,您能为您的问题添加预期结果吗?@MartinPaucot done,谢谢:)哦,是的,当然,我试过了,效果不错!谢谢