2 回答

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是因?yàn)榉秶l(fā)生的,因?yàn)槟鷥H在 if 語(yǔ)句中聲明和定義了 loopingAdjustment 變量,因此范圍僅限于 if 語(yǔ)句。要解決此問題,您可以在 if 之外聲明 loopingAdjustment 并在 if 語(yǔ)句中分配它。您可以從下面的代碼中獲取參考,您可以修改 acc. 根據(jù)您的需要。
const caesar = function(startingString, shiftAmount) {
let itemizedString = startingString.split('');
const mappedLetters = itemizedString.map(stringLetter => {
//turn each letter in array into their respective character code
let thisLetter = stringLetter.charCodeAt(stringLetter);
// checking if character is alphabetic and converting its charcode back to a letter
if (thisLetter < 65 || (thisLetter > 90 && thisLetter < 97) || thisLetter > 122) {
return;
} else {
shiftedLetter = thisLetter + shiftAmount;
}
// making sure the shifted letters loop to beginning, or end, of alphabet
let loopingAdjustment = 0;
if (thisLetter > 96 && shiftedLetter > 122) {
loopingAdjustment = shiftedLetter - 26;
} else if (thisLetter > 96 && shiftedLetter < 96) {
loopingAdjustment = shiftedLetter + 26;
} else if (thisLetter < 91 && shiftedLetter > 90) {
loopingAdjustment = shiftedLetter - 26;
} else if (thisLetter < 91 && shiftedLetter < 65) {
loopingAdjustment = shiftedLetter + 26;
} else {
loopingAdjustment = shiftedLetter;
}
let finalString = String.fromCharCode(loopingAdjustment);
return finalString;
});
console.log(mappedLetters);
return mappedLetters.join('');
}
module.exports = caesar

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
您在 let 有自己的范圍的條件中聲明 loopingAdjustment 。在條件句之外聲明它,只在條件句中更改它的值一次。
添加回答
舉報(bào)