在下面的代码中,我想实现,每当标记值是新的,它应该被添加到一个数组。如果标签不存在,则将添加包含标签和计数器的对象。那也行
不起作用的是,当标签已经存在时,我想增加计数器。不管是什么原因,我得到了一个NaN作为结果。
recipes.js
/* Count apperance of every tag */
let tagCounter = [];
allRecipes.forEach(recipe => {
const tag = recipe.tag;
// Suche nach dem Tag in tagCounter
const existingTag = tagCounter.find(item => JSON.stringify(item.tag) === JSON.stringify(tag));
if (existingTag) {
// Das Tag wurde gefunden, erhöhe den Counter
existingTag.tag.counter += 1;
console.log(existingTag.tag.counter);
} else {
// Das Tag wurde nicht gefunden, füge es zu tagCounter hinzu
tagCounter.push({ tag, counter: 1 });
console.log("else");
console.log(existingTag?.tag?.counter);
}
});
console.log(tagCounter);
res.status(200).json({resultArrayUniqueTags, tagCounter})
控制台:
else
undefined
else
undefined
NaN
NaN
NaN
NaN
[ { tag: Breakfast, counter: 1 }, { tag: Lunch, counter: 1 } ]
我真的不明白为什么我不能增加计数器。当使用console.log(typeof)验证数据类型时,它显示“number”。
1条答案
按热度按时间lsmd5eda1#
您应该执行
existingTag.counter += 1;
而不是existingTag.tag.counter += 1;
此外,
console.log(existingTag.counter);
代替console.log(existingTag.tag.counter);