[英]convert capital letters into small and small letters into capital
var str = "HellO WoRld"
var myArr = str.split(" ");
for(i=0;i<myArr.length;i++)
{
myArr2 =myArr[i].split("");
// console.log(myArr2);
for(j=0;j<myArr2.length;j++)
{
if(myArr2[j].charCodeAt(j) >= 65 && myArr2[j].charCodeAt(j) <= 90 )
{
document.write(myArr2[j].toLowerCase());
}
else if(myArr2[j].charCodeAt(j) >= 97 && myArr2[j].charCodeAt(j) <= 122 )
{
document.write(myArr2[j].toUpperCase());
}
}
}
因此,我一直在嘗試使用charCodeAt()將單詞中的字母從大寫更改為小寫,反之亦然,你們可以告訴我我的代碼有什么問題還是建議替代代碼,但只能使用charCodeAt()。 在我的代碼中,輸入為HellO WoRld,輸出應為hello WORLD,但我將其輸出為hw。
var str = "HellO WoRld" var myArr = str.split(""); for(i=0;i<myArr.length;i++) { myArr2 =myArr[i].split(""); // console.log(myArr2); for(j=0;j<myArr2.length;j++) { if(myArr2[j].charCodeAt(j) >= 65 && myArr2[j].charCodeAt(j) <= 90 ) { console.log(myArr2[j].toLowerCase()); } else if(myArr2[j].charCodeAt(j) >= 97 && myArr2[j].charCodeAt(j) <= 122 ) { console.log(myArr2[j].toUpperCase()); } } }
您的問題在於str.split(" ")
,刪除多余的空間並進行無空間分割應該可以正常工作var myArr = str.split("")
@ line2
我認為您正在濫用charCodeAt
函數。 該功能已經將字符位置作為輸入,但是您要兩次指定該信息,例如
myArr2[j].charCodeAt(j)
而是嘗試以下版本:
var str = "HellO WoRld" var myArr = str.split(" "); var out = ""; for (i=0; i < myArr.length; i++) { var word = myArr[i]; var output = ""; console.log(word); for (j=0; j < word.length; j++) { if (word.charCodeAt(j) >= 65 && word.charCodeAt(j) <= 90) { output += String.fromCharCode(word.charCodeAt(j) + 32); } else if (word.charCodeAt(j) >= 97 && word.charCodeAt(j) <= 122) { output += String.fromCharCode(word.charCodeAt(j) - 32); } } if (out !== "") { out += " "; } out += output; console.log(output); } console.log("final output: " + out);
如果您需要將此輸出寫入DOM,建議您先在JavaScript代碼中構建字符串,然后再進行一次DOM更新,而不是一次添加一個字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.