For-loop根据长度将值更改为大写或小写

问题描述 投票:-1回答:2

我正在尝试创建一个简单的JavaScript程序,它会提示您在页面加载时输入一个句子。然后将该句子分成由空格“”分隔的数组。

我目前的问题是它根本没有将任何东西转换成大写或小写。我似乎无法理解为什么和一些帮助将不胜感激。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>for-loop replacement exercise</title>
    <script language="JavaScript" type="text/JavaScript">
        var wordString = prompt("Please enter a sentence: ", 0);
        var processedString;
        var cont = boolean(true);

        // this function is called upon page startup
        function startMeUp() {
            do {
                wordString;
                if (wordString == "") {
                    cont = boolean(false);
                }
            } while(cont);

            processString(wordString);
            document.write(processedString);
        }

        // this function is attempting to iterate through a array of strings and anything that is 4 characters long it is put to lower case  
        // otherwise if the iteration is less than 4 its put to upper case
        function processString(someInput) {
            var wordArray = someInput.split(" ");
            var lengArray = wordArray.length; 

            for (var i = 0; i < lengArray; i++) {
                if (lengArray[i] == 4) {
                    wordArray[i].toLowerCase();
                } else if (lengArray[i] < 4) {
                    wordArray[i].toUpperCase();
                }
            }
            processedString = wordArray.toString();
        }
    </script>
</head>
    <body onload="startMeUp();">
    </body>
</html>
javascript html arrays
2个回答
0
投票

尝试将返回值赋给数组索引,而不是只调用函数而不是存储它:

wordArray[i] = wordArray[i].toLowerCase();

-1
投票

首先你没有打电话给startMeUp(),所以我补充说。接下来,您可以使用map()简化代码。

var wordString = prompt("Please enter a sentence: ", '');
startMeUp();

function startMeUp() {
  document.write(processString(wordString));
}

function processString(someInput) {
  return someInput.split(" ").map(v => {
    if (v.length == 4) return v.toLowerCase()
    if (v.length < 4) return v.toUpperCase()
    return v
  }).join(' ')
}
© www.soinside.com 2019 - 2024. All rights reserved.