这个js控制台的undefined是从哪里冒出来的?

没想出来这个undefined是从哪里冒出来的。。。。
clipboard.png

<script>
    count=0
    function foo(){
        t1=new Date()
        console.log("foo执行",t1.toLocaleString(),"count=",count)
    }
    t=new Date()
    console.log("开始",t.toLocaleString())
    var interval
    interval=setInterval(function(){
        if(count==5){
            console.log("count=15,开始清理")
            clearInterval(interval)
            console.log("清理结束")
            console.log(console.log("清理interval",t.toLocaleString(),"count=",count))
        }
        t=new Date()
        setTimeout(foo,10000)
        console.log("+","interval执行",t.toLocaleString(),"count=",count)
        count++
    },1000)
</script>>
  • interval执行 2018/1/30 下午5:41:52 count= 0

testfiled.html:34 + interval执行 2018/1/30 下午5:41:53 count= 1
testfiled.html:34 + interval执行 2018/1/30 下午5:41:54 count= 2
testfiled.html:34 + interval执行 2018/1/30 下午5:41:55 count= 3
testfiled.html:34 + interval执行 2018/1/30 下午5:41:56 count= 4
testfiled.html:27 count=15,开始清理
testfiled.html:29 清理结束
testfiled.html:30 清理interval 2018/1/30 下午5:41:56 count= 5
testfiled.html:30 undefined
testfiled.html:34 + interval执行 2018/1/30 下午5:41:57 count= 5
testfiled.html:20 foo执行 2018/1/30 下午5:42:02 count= 6
testfiled.html:20 foo执行 2018/1/30 下午5:42:03 count= 6
testfiled.html:20 foo执行 2018/1/30 下午5:42:04 count= 6
testfiled.html:20 foo执行 2018/1/30 下午5:42:05 count= 6
testfiled.html:20 foo执行 2018/1/30 下午5:42:06 count= 6
testfiled.html:20 foo执行 2018/1/30 下午5:42:07 count= 6

阅读 3.1k
5 个回答
//大概没注意,多写了一层console.log();
console.log(console.log("清理interval",t.toLocaleString(),"count=",count))

// myVar的值为undefined
var myVar = console.log("清理interval",t.toLocaleString(),"count=",count);
console.log(myVar);

console.log没有返回值

        if(count==5){
            console.log("count=15,开始清理")
            clearInterval(interval)
            console.log("清理结束")
            //下面一嵌套了一层console.log
            console.log(console.log("清理interval",t.toLocaleString(),"count=",count))
        }

这个undfined来自你调用的某个没有手动return的方法。
这个方法可能是你写的也可能是来自js内部的,因为我们知道一个方法如果没有手动return的话会默认返回undefined
最简单的例子就是

console.log('anything');

的控制台输出,如下

clipboard.png
这个undefined就来自js的console.log方法,因为他没有手动return。

console.log(console.log("清理interval",t.toLocaleString(),"count=",count))

多了一个 console.log

弱弱的说一句,末尾那里不是写着行号呢么,点进去看一眼相应行的代码不就知道了……

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题