在javascript的find array函数中,与常量的比较不起作用,而与字符串的直接比较起作用

在javascript的find array函数中,与常量的比较不起作用,而与字符串的直接比较起作用,javascript,node.js,find,Javascript,Node.js,Find,以下代码不起作用: try { const _id = req.params.id await req.user.populate("tasks").execPopulate(); console.log("_id: ",_id) console.log("_id type", typeof(_id)) //console.log(req.user.tasks); const task = await req.u

以下代码不起作用:

try {
  const _id = req.params.id
  await req.user.populate("tasks").execPopulate();
  console.log("_id: ",_id)
  console.log("_id type", typeof(_id))
  //console.log(req.user.tasks);
  const task = await req.user.tasks.find(o =>
    o._id.toString() === _id)
  updates.forEach((update) => task[update] = req.body[update])
  await task.save();
以下是控制台输出:

_id:  5f1b5164acfd1a264d1589d5

src/routers/task.js:68
_id type string
src/routers/task.js:69
task: undefined
而如果我改变这一行:

  const task = await req.user.tasks.find(o =>
    o._id.toString() === _id)
为此:

  const task = await req.user.tasks.find(o =>
    o._id.toString() === "5f1b5164acfd1a264d1589d5")
它工作得很好。有人知道为什么吗


附加信息:如评论中所述,我查看了每个字符串中的确切字符:

console.log(_id.split(“”).map(x=>x.charCodeAt(0)))
/*
[
53, 102, 49, 98, 53, 49, 54, 52, 97, 99,
102, 100, 49, 97, 50, 54, 52, 100, 49, 53,
56, 57, 100, 53, 10
]
*/
console.log(“5f1b5164acfd1a264d1589d5”.split(“”).map(x=>x.charCodeAt(0)))
/*
[
53, 102, 49, 98, 53, 49, 54, 52, 97, 99,
102, 100, 49, 97, 50, 54, 52, 100, 49, 53,
56, 57, 100, 53
]
*/

\u id
值的末尾有一个换行字符(字符代码10或JavaScript中的
\n

事实上,这甚至可以在调试输出中看到-打印ID后会出现一个空行。我建议使用调试器并单步执行代码,以这种方式查看变量,而不是使用
console.log
。它可能会将字符串显示为“5f1b5164acfd1a264d1589d5\n”

您可以使用
.trim
,删除字符串中的所有前导和尾随空白:

const\u id=req.params.id.trim()
这样,代码就可以工作了,尽管有多余的换行符传递到URL中



然而,这应该让你想知道,这怎么可能发生在第一位。当我看到这个问题时,我最初排除了这样的问题,因为
\u id
似乎来自URL路径参数
req.params.id
,并且换行符不是URL中的有效字符,除非您显式地将其作为
%0A
传入,我一开始不太可能这样做。您应该仔细检查这个URL的来源,因为实际的bug可能来自那里

您是否100%确定
o.\u id.toString()===\u id
不起作用,而
o.\u id.toString()===“5f1b5164acfd1a264d1589d5”
起作用?因为对于您显示的输出(以及来自URL路径参数的字符串,因此不会出现任何BOM表或换行符等问题),这两种方法都应该有效。只是一种感觉-也许你最初没有
.toString()
(因为那样它确实不起作用,因为
o._id
是一个
ObjectId
而不是字符串)?我100%肯定。试了好几次。刚才又试了一次。这真的很奇怪。请检查
\u id.split(“”).map(x=>x.charCodeAt(0))
的输出,并将其与使用字符串文字(
“5f1b5164acfd1a264d1589d5.split(“”).map(x=>x.charCodeAt(0))
执行的相同操作进行比较。id常量:[53、102、49、98、53、49、54、52、97、99、102、100、49、97、50、54、52、100、49、53、56、57、100、53、10]id字符串:[53、102、49、49、98、53、49、54、97、99、102、100、49、97、50、54、52、100、49、53、56、57、100、53]这似乎与linefeed有关。我在windows计算机上,是否相关?嗨。请求来自postman。我在windows计算机上,我下载了我现在正在使用的源文件。可能一些.js文件有LF而不是CRLF,这导致了问题?在postman中的url字段中有一个换行符: