向字符串原型对象添加用于交换大小写的函数 - JavaScript

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/12 10:20:17

在 JavaScript 中,我们可以编写自己的自定义函数并将它们分配给现有的标准数据类型(这与编写库方法非常相似,但在这种情况下,数据类型是原始的,而不是用户定义的。我们需要编写一个名为 swapCase() 的 JavaScript 字符串函数。

此函数将返回一个新字符串,其中所有大写字符都交换为小写字符,反之亦然。任何非字母字符都应保持原样。

示例

以下是代码 −

const str = 'ThIS iS A CraZY StRInG';
String.prototype.swapCase = function(){
   let res = '';
   for(let i = 0; i < this.length; i++){
      if(this[i].toLowerCase() === this[i].toUpperCase()){
         res += this[i];
         continue;
      };
      if(this[i].toLowerCase() === this[i]){
         res += this[i].toUpperCase();
         continue;
      };
      res += this[i].toLowerCase();
   };
   return res;
};
console.log(str.swapCase());

输出

以下是控制台中的输出 −

tHis Is a cRAzy sTriNg

相关文章


有用资源