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
相关产品推荐
相关产品推荐

