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

Node.js与Express中数组length拼写错误致id出现NaN问题

问题解决:id生成NaN的原因与修复
  • 核心问题:你把数组的length属性拼写成了lenght(少了字母t)。数组不存在lenght这个属性,所以person.lenght会返回undefined,undefined + 1自然得到NaN。

  • 修正后的代码:

app.post('/add', (req, res) => { 
  const newperson = {
    id: person.length + 1, // 修正拼写错误:lenght → length
    Text: req.body.text,
    Type: req.body.type
  }
  person.push(newperson)
  console.log(person.slice(-1))
  res.json(newperson)
})
  • 额外优化建议:
    • 如果后续有删除数组元素的操作,仅用person.length + 1生成id可能出现重复id。可以改用数组中最大id加1的方式生成新id:
      const maxId = person.length > 0 ? Math.max(...person.map(item => item.id)) : 0;
      id: maxId + 1
      
    • 确保person数组在当前路由的作用域内可正常访问,避免因作用域问题引发其他异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 08:25:57