gpt4 book ai didi

javascript - 如何创建/打印用户定义的(输入)数组,在 for-each 函数中对输入没有限制

转载 作者:行者123 更新时间:2023-11-28 03:41:18 24 4
gpt4 key购买 nike

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

这应该按照我想的方式打印。

关于javascript - 如何创建/打印用户定义的(输入)数组,在 for-each 函数中对输入没有限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57283800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com