我创建了一个更改大小写的脚本,但是在文本上使用它的结果完全相同,没有一个更改.有人可以解释一下吗?
var swapCase = function(letters){ for(var i = 0; i<letters.length; i++){ if(letters[i] === letters[i].toLowerCase()){ letters[i] = letters[i].toUpperCase(); }else { letters[i] = letters[i].toLowerCase(); } } console.log(letters); } var text = 'So,today we have REALLY good day'; swapCase(text);
解决方法
就像伊恩说的那样,你需要建立一个新的字符串.
var swapCase = function(letters){ var newLetters = ""; for(var i = 0; i<letters.length; i++){ if(letters[i] === letters[i].toLowerCase()){ newLetters += letters[i].toUpperCase(); }else { newLetters += letters[i].toLowerCase(); } } console.log(newLetters); return newLetters; } var text = 'So,today we have REALLY good day'; var swappedText = swapCase(text); // "sO,TODAY WE HAVE really GOOD DAY"