Javascript 如何区分nodejs中setInterval的返回值

Javascript 如何区分nodejs中setInterval的返回值,javascript,node.js,Javascript,Node.js,nodejs中setInterval的返回值不是一个数字,而是一个对象。那么如何识别返回的计时器对象?以下console.log仅打印[object] res.writeHead(200, { 'Connection': 'keep-alive', 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); const id=setInterval(f

nodejs中setInterval的返回值不是一个数字,而是一个对象。那么如何识别返回的计时器对象?以下console.log仅打印[object]

  res.writeHead(200, {
        'Connection': 'keep-alive',
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache'
      });
  const id=setInterval(function(){

      res.write('data:helloworld! \n\n');

    }, 1000);
  console.log("to begin:interval id is "+id)

  req.on("close",function(){
    console.log("to end:interval id is "+id)
    clearInterval(id)
  })

如果您试图在这里做的是在日志中识别不同的计时器,以便将日志消息与特定计时器关联,那么您可以在每个计时器对象上放置一个可识别的属性,然后记录该id值

  // variable declared at a module level scope so it persists:
  let timerCntr = 1;

  // code inside your request handler

  res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache'
  });

  const timer = setInterval(function() {
      res.write('data:helloworld! \n\n');
  }, 1000);
  // assign ID to the timer object
  timer.myid = timerCntr++;
  console.log("to begin:interval id is " + timer.myid)

  req.on("close", function() {
      console.log("to end:interval id is " + timer.myid)
      clearInterval(timer);
  })

我如何确定
目的。你存储它,你使用它,为什么你需要“识别”它-注意:在控制台中将
+id
更改为
,id
。要查看对象的内容,你只需将新的
Timeout
对象存储在一个数组中,并通过将索引视为id来引用它。计时器是对象,而不是整数或字符串id。将计时器对象输出到控制台,就像输出任何其他对象
console.log(id)
,而不是
console.log(“somestring”+id)
。如果您想识别一个非常特定的ID用于日志记录,那么您可能应该在timer对象上放置自己的数值或字符串属性,然后将其输出到控制台。但是,除此之外,我们根本不清楚你们到底想解决什么问题。在Javascript中执行
“some string”+obj
可以获得
一些字符串[object object]
。它就是这样做的。这是看物体的错误方式。