2013-03-19 32 views
2

所以,我想要做的是創建一個函數,允許用戶輸入一個字符串,然後它將輸出拉丁字符串。這是我現在的功能:修改數組中的每個單詞

function wholePigLatin() { 
      var thingWeCase = document.getElementById("isLeaper").value; 
      thingWeCase = thingWeCase.toLowerCase(); 
      var newWord = (thingWeCase.charAt(0)); 

      if (newWord.search(/[aeiou]/) > -1) { 
       alert(thingWeCase + 'way') 
      } else { 
       var newWord2 = thingWeCase.substring(1, thingWeCase.length) + newWord + 'ay'; 
       alert(newWord2) 
      } 
     } 

我如何得到它,讓它識別每一個字,然後修改每個字,我有上面的方法是什麼?

+1

如果只是簡單的字符串的話,我想你需要分割基於空間==>字符串分割(」「) ; – 2013-03-19 16:04:19

回答

0

使用javascript的split()方法。在這種情況下,你可以做var arrayOfWords = thingWeCase.split(" ") 這將字符串分割成一個字符串數組,分割點位於每個空格處。然後,您可以輕鬆瀏覽結果數組中的每個元素。

+0

太棒了!我明白你在那裏做什麼。一旦我用新變量分割數組,我該如何通過函數發送數組的每一塊? – 2013-03-19 16:05:45

+0

以及由你決定。我會做一個for循環並遍歷每個元素,對每個元素執行拉丁方法。最後,你可以使用'var sentence = str1 +「」+ str2 ...將它們連接在一起...' – Cristiano 2013-03-19 16:08:40

+1

@AlanJosephSylvestre https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/地圖 – Andreas 2013-03-19 16:09:03

0

寫,在一個循環中調用您的單個詞的功能的功能:

function loopPigLatin(wordString) { 
    words = wordString.split(" "); 
    for(var i in words) 
    words[i] = wholePigLatin(words[i]); 
    return words.join(" "); 
} 

當然,要這樣稱呼它,你會希望你的原始功能略有變化:

function wholePigLatin(thingWeCase) { 
    // everything after the first line 
    return newWord2; // add this at the end 
} 

然後調用loopPigLatin這樣的:

document.getElementById("outputBox").innerHTML = loopPigLatin(document.getElementById("isLeaper").value); 
1

修改函數取一個參數並返回值

function wholePigLatin(thingWeCase) { 
    thingWeCase = thingWeCase.toLowerCase(); 
    var newWord = (thingWeCase.charAt(0)); 

    if (newWord.search(/[aeiou]/) <= -1) { 
     newWord = thingWeCase.substring(1, thingWeCase.length) + newWord + 'ay'; 
    } 
    else{ 
     newWord = thingWeCase + 'way'; 
    } 
    return newWord; 
} 

,那麼你可以這樣做:

var pigString = str.split(" ").map(wholePigLatin).join(" "); 

這將字符串分割成單詞,每個單詞傳遞給函數,然後用空格加盟輸出重新走到一起。

另外,如果您總是希望從同一個源獲取數據,您可以從該函數內獲取數組並將其拆分/連接。

+0

這看起來像ti將完全正確!我在哪裏把var pigString放在函數中? – 2013-03-19 16:33:05

+0

下面是一個示例用法的小提琴。你究竟如何使用它取決於你對字符串做了什麼以及你從哪裏得到原始信息。 http://jsfiddle.net/eSgC2/2/ – 2013-03-19 16:52:01

0

你可以只匹配單詞,正則表達式,並與回調替換它們。

var toPigLatin = (function() { 
    var convertMatch = function (m) { 
     var index = m.search(/[aeiou]/); 
     if (index > 0) { 
      return m.substr(index) + m.substr(0,index) + 'ay'; 
     } 
     return m + 'way'; 
    }; 
    return function (str) { 
     return str.toLowerCase().replace(/(\w+)/g, convertMatch); 
    }; 
}()); 

console.info(toPigLatin("lorem ipsum dolor.")); // --> oremlay ipsumway olorday.