javascript在回调函数内分配变量返回undefined

时间:2016-06-29 09:22:32

标签: javascript

我有一个简单的脚本来播放音频:

        var audio = new Audio(music)
        var music_duration
        audio.addEventListener('loadedmetadata', function() {
            var duration = audio.duration
            console.log(duration)
            music_duration = duration
        })

        console.log("checking duration")
        console.log(music_duration)

此处music_duration返回undefined ..

duration内的addEventListener给出了音乐的持续时间。

我是javascript的新手......这里有什么问题?

1 个答案:

答案 0 :(得分:0)

console.log("checking duration")
console.log(music_duration) 

将在 loadedmetadata 事件发出之前执行。

您可以通过以下方式检查脚本编辑:

    var audio = new Audio(music)
    var music_duration
    audio.addEventListener('loadedmetadata', function() {
        console.log('here')
        var duration = audio.duration
        console.log(duration)
        music_duration = duration
    })
    console.log('there')
    console.log("checking duration")
    console.log(music_duration)

您会在there之前看到here