簡體   English   中英

修改數組的每個單詞

[英]Modifying each word of an array

因此,我想做的是創建一個函數,該函數允許用戶輸入字符串,然后將其輸出為豬拉丁字。 現在是我的功能:

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)
            }
        }

我如何獲得它以便識別每個單詞,然后按照上面的方式修改每個單詞?

修改函數以接受參數並返回值

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(" ");

這會將字符串拆分為單詞,將每個單詞傳遞給函數,然后將輸出與空格重新連接在一起。

另外,如果您總是想從同一源獲取數據,則可以從函數內部獲取數組並拆分/合並它。

使用javascript的split()方法。 在這種情況下,您可以執行var arrayOfWords = thingWeCase.split(" ")這會將字符串拆分為字符串數組,拆分點位於每個空格處。 然后,您可以輕松遍歷結果數組中的每個元素。

編寫一個循環調用單字函數的函數:

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);

您可以使用regexp匹配單詞並將其替換為callback:

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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM