簡體   English   中英

如何在for-each函數中創建/打印用戶定義的(輸入)數組,且輸入沒有限制

[英]how to create / print a user-defined (input) array with no limit for input in a for-each function

- Prompt the user to enter the word list and assign the input to a variable. Consider using the prompt() method to retrieve the user’s input. ..* Example: var input = prompt(‘Enter words separated by a space’);
- Split the word list where the separator is a space " ". Assign it to a variable. Consider using the split() method to split the word list on the spaces. Example: var wordList = input.split(" ");
- Create another array to store the number each word appears in the list of words (array).
- For each word in the list of words (wordlist), check to see if each word exists in the list (array). Consider using the forEach() method. This method is called once for each element in the array, in order. Example: wordList.forEach ( …….); HINT: Inside of the forEach() method consider using a branching statement to determine if the word exists in the list. If it exists, increase the counter. If it doesn’t exist, keep the counter at 1.
- Print each word along with the number the word exists in the list. Consider using the forEach() method again to print each element in both arrays.

我已完成上述所有步驟,但是只需要幫助打印單詞出現的次數即可。 在我的console.log語句中,單詞會打印到控制台,所以現在我只需要幫助弄清楚如何打印單詞在單詞列表中出現的頻率。

function calcWordFrequencies(){
var input = prompt('Enter words separated by a space');
var wordList = input.split(" ");
var wordCounts = { };

wordList.forEach(
    function(word) {
    if(word in wordCounts)
    {
        wordCounts[word] = wordCounts[word] + 1;
    }else{
        wordCounts[word] = 1;
    }//end of if/else statement
}//end of function
);//end of for-each function
wordList.forEach(
    function(word) {
    console.log(word + wordCounts);
}
);
}

這是一個隨機輸出的示例:

hey 1
hi 2
Mark 1
hi 2
mark 1
    function calcWordFrequencies(){
    var input = prompt('Enter words separated by a space');
    var wordList = input.split(" ");
    var wordCounts = { };

    wordList.forEach(
        function(word) {
        if(word in wordCounts)
        {
            wordCounts[word] = wordCounts[word] + 1;
        }else{
            wordCounts[word] = 1;
        }//end of if/else statement
    }//end of function
    );//end of for-each function
    for(let word in wordCounts)
    { 
      document.write(word + " : " + wordCounts[word] + "\n");
    } 
  }

這應該打印出您想要的方式。

暫無
暫無

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

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