首页 > 解决方案 > JS在字符串中每隔一个字符切换大小写

问题描述

该函数应该接受一个字符串并每隔一个字符切换一次的大小写。例如:

input: 'HelloWorld'  output: 'HElLowoRlD'
input: 'abcdefg'  output: 'aBcDeFg'
input: 'TONYmontana'  output: 'ToNymOnTaNa'

我的功能不起作用,为什么?

function switchCase(text) {
  for (let i = 0; i < text.length; i++) {
    if (i % 2 !== 0) {
      if (text[i] === text[i].toLowerCase()) {
        text[i] = text[i].toUpperCase();
      } else {
        text[i] = text[i].toLowerCase();
      }
    }
  }
  return text;
}

标签: javascript

解决方案


您应该将新值存储在字符串中并从函数中返回:

function secondCase(text) {
  let newValue = ''; // declare a variable
  for (let i = 0; i < text.length; i++) {
    if(i % 2 !== 0) {
      if (text[i] === text[i].toLowerCase()) {
        newValue += text[i].toUpperCase();  // concatenate the modified letter
      }
      else {
        newValue += text[i].toLowerCase(); // concatenate the modified letter
      }
    }
    else newValue += text[i]; // concatenate the unmodified letter
  }
  return newValue; // return
}

console.log(secondCase('HelloWorld'));
console.log(secondCase('abcdefg'));
console.log(secondCase('TONYmontana'));


推荐阅读