javascript - 无法在 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();
}
解决方案
一件事是,您需要初始化arrpla
(大概为 0):而不是
arrpla:number;
做
arrpla = 0;
(将推断类型)。
但我看到了另一个潜在的问题:this
绑定。恐怕这里
this.audioObj.onended=this.playnext;
的this
绑定playnext
可能会丢失。所以你可能会undefined + 1 makes NaN
因为arrpla
从未定义过,或者因为回调没有得到正确的this
对象。
我会将您的方法转换为箭头函数:替换
playnxt() {
和
playnxt = () => {
推荐阅读
- vba - 获取文件夹和子文件夹中的列表文件
- ios - “reserveCapacity”函数如何与 Swift 中的“Dictionary”CollectionType 一起使用?
- javascript - 影响日期范围选择器弹出对话框的 HTML 表格样式
- python - 如何使用 Django 的 CheckConstraint 在数据库级别限制变量?
- pandas - dtype=datetime64[ns, UTC] 和 Timestamp 之间的无效比较
- c++ - 使用 mixin 强制执行模板化基类类型
- reactjs - 试图在课堂上取得成功
- c++ - 从接收到的路径中删除
- haskell - Haskell“threeRoundFight”通过嵌套 lambdas 覆盖变量
- dataframe - 如何从带有标头的 XLSX.readdata() 对象创建 DataFrame?