无法读取 Audio.playnxt 中未定义的属性“NaN”
2020-06-24
492
当我尝试播放当前正在播放的歌曲末尾的数组列表中的下一首歌曲时出现以下错误。
*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();
}
2个回答
有一件事是,您需要初始化
arrpla
(大概为 0):而不是
arrpla:number;
做
arrpla = 0;
(类型将被推断)。
但我看到另一个潜在的问题:
this
绑定。我担心这里
this.audioObj.onended=this.playnext;
playnext
的
this
绑定可能会丢失。因此,您可能会得到
undefined + 1 makes NaN
,因为
arrpla
从未定义,或者因为回调没有获得正确的
this
对象。
我会将您的方法转换为箭头函数:将
playnxt() {
替换为
playnxt = () => {
mbojko
2020-06-24
在代码第 3 行,您声明
arrpla:number;
arrpla
当前为
undefined
并且当您执行
var i=this.arrplaa;
时,
i
也是
undefined
。
在 javascript 中
undefined+1
变为
NaN
,因此
i=i+1
可被视为
i=undefined + 1 // NaN
因此您在此处可以做的是使用
arrpla:number=0;
将
arrpla 初始化为 0
希望这有帮助。
namar sood
2020-06-24