iT邦幫忙

0

詢問JS 轉換大小寫問題

  • 分享至 

  • xImage

不好意思小弟我目前在自學JS,在寫練習題時碰到問題就是當輸出後Console.log顯示出空值,詢問程式碼是哪裡出問題(以下附上程式碼),還請各位大佬幫幫忙!
https://ithelp.ithome.com.tw/upload/images/20230915/20163277o1gA6f4sOI.png
輸出後未顯示出轉換文字
https://ithelp.ithome.com.tw/upload/images/20230915/2016327750gNeRy6Fp.png
更新:
for 迴圈裡的長度length 拼錯 感謝

淺水員 iT邦大師 6 級 ‧ 2023-09-15 13:19:33 檢舉
有個小細節可以再研究一下
其實有些字的 length 是 2 而不是 1
例如化學元素「金木土」這個字
淺水員 iT邦大師 6 級 ‧ 2023-09-15 13:21:46 檢舉
這牽涉到 UCS-2 編碼的代理對
可參考:https://zh.wikipedia.org/zh-tw/UTF-16
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
Annie
iT邦新手 2 級 ‧ 2023-09-15 12:13:11

我這邊測試應該沒問題耶
你的 length 拚對後,其實是可以正常印出的。

還是再附上一次程式碼,建議再測試看看:

function swapr(str) {
	let tempArray = [];
	for (let i = 0; i <str.length; i++) {
		if(str[i].charCodeAt() >= 65 && str[i].charCodeAt() <= 90) {
			tempArray.push(String.fromCharCode((str[i].charCodeAt() + 32)));
		} else if (str[i].charCodeAt() >= 97 && str[i].charCodeAt() <= 122) {
			tempArray.push(String.fromCharCode((str[i].charCodeAt() - 32)));
		} else {
			tempArray.push(str[i]);
		}
	};
	
	return tempArray.join('');
};

console.log(swapr('Peter'));

我要發表回答

立即登入回答