You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

标签存在时计数器递增出现NaN问题求助

标签计数器递增返回NaN的问题修复

问题描述

我要实现的逻辑是:遍历食谱列表,遇到新标签就添加到统计数组;标签已存在则递增计数器。新增标签的逻辑正常,但递增时始终返回NaN,控制台输出也显示计数器变为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 } ]

我检查过数据类型为number,但仍出现NaN,无法定位问题。


核心错误原因

你在递增计数器时访问了existingTag.tag.counter,但实际上数组元素的结构是{ tag: 标签值, counter: 数字 }——counter是直接属于数组元素对象的属性,并非tag的子属性。

第一次添加标签时,tagCounter.push({ tag, counter: 1 })创建的对象是{ tag: 'Breakfast', counter: 1 },而非{ tag: { value: 'Breakfast', counter:1 }, ... }。因此existingTag.tag.counter相当于访问一个不存在的属性,初始值为undefined,undefined + 1就会得到NaN。


修正后的代码

/* Count apperance of every tag */
let tagCounter = [];
allRecipes.forEach(recipe => {
    const tag = recipe.tag;

    // 查找已存在的标签
    const existingTag = tagCounter.find(item => JSON.stringify(item.tag) === JSON.stringify(tag));
    if (existingTag) {
        // 直接递增counter属性
        existingTag.counter += 1;
        console.log(existingTag.counter);
    } else {
        // 添加新的标签统计项
        tagCounter.push({ tag, counter: 1 });
        console.log("else");
    }
});

console.log(tagCounter);
res.status(200).json({resultArrayUniqueTags, tagCounter})

额外优化建议

如果你的tag是字符串类型,无需使用JSON.stringify比较,直接用item.tag === tag更高效:

const existingTag = tagCounter.find(item => item.tag === tag);

内容的提问来源于stack exchange,提问作者IHateCoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:28:28