gpt4 book ai didi

javascript - 通过循环将对象添加到数组中的正确方法

转载 作者:行者123 更新时间:2023-12-02 20:53:59 26 4
gpt4 key购买 nike

我知道这是一个重复的问题,但我无法找出将对象添加到数组并检查是否匹配的正确方法,这是一个循环遍历单词数组并检查是否存在的函数输入的单词在数组中,因此将其计数增加 1 ,如果没有,则将此单词插入数组并将其计数设置为 0

function addWord(request, response) {
var data = request.params;
var word = data.word;
var reply;
for (i = 0; i < Words.length; i++){
if (Words[i].type != word){
reply = {
msg: "not Found but added"
};
Words.push({"type": word , "count": 0});
} else if (Words[i].type == word) {
reply = {
msg: "already Found and added"
};
Words.count++;

}

}




var x = JSON.stringify(Words, null, 2);
fs.writeFile('count.json', x, finished);

function finished(){
console.log('Yay')
}

问题是输出给了我四个新元素,而不仅仅是一个,并且计数为1而不是0,假设我添加了单词音乐,输出就像这样

[
{
"type": "physical",
"count": 8
},
{
"type": "WCAP",
"count": 2
},
{
"type": "BLQ",
"count": 2
},
{
"type": "unable",
"count": 2
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
{
"type": "music",
"count": 1
},
]

最佳答案

问题在于,您首先必须循环遍历所有单词,然后才能确定某个单词是否在列表中。您可以将代码修改为如下所示:

var found = false

for (i = 0; i < Words.length; i++){
if (Words[i].type == word){
Words[i].count++
reply = {
msg: "already Found and added"
};
found = true;
break;
}
}

if (!found) {
Words.push({"type": word , "count": 0});
reply = {
msg: "already Found and added"
};
}

为了以防万一,这里有一个包含更简单的 addWord 函数的代码片段,可能会对您有所帮助:

var Words = [];

function addWord(word) {
for (var i=0; i < Words.length; i++) {
if (word == Words[i].type) {
Words[i].count++
return
}
}

Words.push({type: word, count: 0})
}

addWord('stack')
addWord('overflow')
addWord('stack')

console.log(Words)

关于javascript - 通过循环将对象添加到数组中的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61535165/

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