Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
373 views
in Technique[技术] by (71.8m points)

一个函数,每秒打印num-1,到0停止?

代码如下所示,通过if,else的形式没什么问题,但是通过 num>=0?console.log(num--):clearInterval(timer),这种三目表达式的形式提示错误,什么原因导致的怎么改?
image.png

function a(num){
  const timer=setInterval(()=>{ 
    num>=0?console.log(num--):clearInterval(timer)
//     if(num>=0){
//       console.log(num--)
//     }else{
//       clearInterval(timer); 
//     }
  },1000)
}
a(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

image.png

a = function a(n) {
  if (n > 0) {
    console.log(new Date().toLocaleString(), n - 1)
    setTimeout(function () { a(n-1) }, 1000)
  }
}
a(5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...