修改数组中的每个单词

Modifying each word of an array

本文关键字:单词 数组 修改      更新时间:2023-09-26

所以,我要做的是创建一个函数,允许用户输入一个字符串,然后它将以猪拉丁文输出字符串。下面是我的函数:

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.