首页 > 解决方案 > 无法在 Audio.playnxt 读取未定义的属性“NaN”

问题描述

当我尝试在当前播放的歌曲末尾播放数组列表中的下一首歌曲时,出现以下错误。

*LocalException: TypeError: Cannot read property 'NaN' of undefined at Audio.playnxt* 
[as __zone_symbol__ON_PROPERTYended] (http://localhost:4200/main.js:484:44) at Audio.wrapFn (http://localhost:4200/polyfills.js:1231:43) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:412:35) at Object.onInvokeTask (http://localhost:4200/vendor.js:53332:33) at ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:411:40) at Zone.runTask (http://localhost:4200/polyfills.js:180:51) at ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:493:38) at invokeTask (http://localhost:4200/polyfills.js:1634:18) at Audio.globalZoneAwareCallback (http://localhost:4200/polyfills.js:1660:21)
i: NaN
this: audio
Closure (./src/app/listenn-read/listenn-read.component.ts)
ListennReadComponent: class ListennReadComponent
ListennReadComponent_a_3_Template: ƒ ListennReadComponent_a_3_Template(rf, ctx)
_Shared_track_model__WEBPACK_IMPORTED_MODULE_1__: Module
track: (...)
Symbol(Symbol.toStringTag): "Module"
__esModule: true
get track: ƒ ()
__proto__: Object
_angular_core__WEBPACK_IMPORTED_MODULE_0__: Module {…}
_c0: Array(1)
0: "test"
length: 1

这是代码:

listenlist:track[];
audioObj=new Audio();
arrpla:number;
len:number=0;    //length of array calculates in constructor
constructor() {
    this.listenlist=[new track('chapter1','chp1name','./assets/C1.mp3'),
                     new track('chapter2','chp2name','./assets/C2.mp3'),
                     new track('chapter3','chp3name','./assets/C3.mp3')]
    this.len=this.listenlist.length;
}

play(url) {
    this.audioObj.src=url;
    this.audioObj.load();
    this.audioObj.play();
    this.audioObj.onended=this.playnext;   //calling the next function to play the next song in the list on end of the currently running song
}

playnxt() {
    var i=this.arrplaa; // i is NaN here
    i=i+1;
    if(i>=this.len){
        i=0;
    }
    this.arrpla=i;
    this.audioObj.src=this.listenlist[i].url; // this is where the exception happens
    this.audioObj.load();
    this.audioObj.play();
}

标签: javascriptnan

解决方案


一件事是,您需要初始化arrpla(大概为 0):而不是

arrpla:number;

arrpla = 0;

(将推断类型)。

但我看到了另一个潜在的问题:this绑定。恐怕这里

this.audioObj.onended=this.playnext;

this绑定playnext可能会丢失。所以你可能会undefined + 1 makes NaN因为arrpla从未定义过,或者因为回调没有得到正确的this对象。

我会将您的方法转换为箭头函数:替换

playnxt() {

playnxt = () => {

推荐阅读