zoukankan      html  css  js  c++  java
  • JavaScrip t将单词的字母按大小写间隔写出

    Description:

    Write a function 'toWeirdCase' ('weirdcase' in Ruby) that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.

    The passed in string will only consist of alphabetical characters and spaces(' '). Spaces will only be present if there are multiple words. Words will be separated by a single space(' ').

    Examples:
    console.log(toWeirdCase( "String" ));   // "StRiNg"
    console.log(toWeirdCase( "Weird string case" ));    //"WeIrD StRiNg CaSe"
    

    my answer:

    function toWeirdCase(arrr){
      var arr= arrr.toLowerCase().split(' ');
      var arrnew =[];
      for(var j=0;j<arr.length;j++){
      var str=arr[j];
      var newStr = '';
      for(var i=0;i<str.length;i+=2){ 
         if(typeof(str[i+1])!='undefined'){  
             newStr += str[i].toUpperCase()+str[i+1].toLowerCase();
         }else{
             newStr += str[i].toUpperCase();
         }
      }
      arrnew.push(newStr);
    }
    return arrnew.join(' ') ;
    }
    
    console.log(toWeirdCase("Weird string case"));  // WeIrD StRiNg CaSe
    console.log(toWeirdCase( "String" ));  // StRiNg
    

    other answer:用map()

    array.map(function(currentValue,index,arr), thisValue)
    
    currentValue(必须)当前元素的值
    index (可选)     当前元素的索引值
    arr (可选)       当前元素属于的数组对象
    thisValue(可选)  对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
                      如果省略了 thisValue ,"this" 的值为 "undefined"
    
    • map()方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
    • map() 方法按照原始数组元素顺序依次处理元素。
    • map() 不会对空数组进行检测。
    • map() 不会改变原始数组。
    function toWeirdCase(string){
      return string.split(' ').map(function(word){
        return word.split('').map(function(letter, index){
          return index % 2 == 0 ? letter.toUpperCase() : letter.toLowerCase()
        }).join('');
      }).join(' ');
    }
    

    或者如下表示

    function toWeirdCaseCharacter(letter, index){
      return index % 2 ? letter.toLowerCase() : letter.toUpperCase();
    }
    function toWeirdCaseWord(word){
      return word.split("").map(toWeirdCaseCharacter).join("");
    }
    function toWeirdCase(string){
      return string.split(" ").map(toWeirdCaseWord).join(" ");
    }
    
  • 相关阅读:
    《哈佛大学公开课:公正该如何做是好?》学习笔记3
    iPhone客户端开发笔记(三)
    iPhone客户端开发笔记(一)
    今天讨论了下本地化服务信息应用
    云游第一天感受
    昨晚调试一段PHP程序时遇到的三个问题
    iPhone客户端开发笔记(四)
    《哈佛大学公开课:公正该如何做是好?》学习笔记2
    Oracle10g数据库归档与非归档模式下的备份与恢复
    javascript 实现页面间传值
  • 原文地址:https://www.cnblogs.com/kid2333/p/7458705.html
Copyright © 2011-2022 走看看