带有数组的 Javascript getter/setter:如何根据数组项索引自动设置属性?
假设我有一个像这样的 playlist
类:
class playlist{
constructor(urls){
this.tracks=urls;
}
}
我想使用 javascript setter 以根据 url 输入创建 track
对象数组。
class track{
constructor(url,num){
this.url=url;
this.num = num;
}
}
class playlist{
constructor(urls){
this.tracks=urls;
}
//tracks setter
set tracks(urls){
this.tracks = urls.map(function(url,index) {
return new track(url,index+1);
})
}
}
这很好。
但是,如果我删除 playlist
对象的 tracks 数组中的某些项目,如果我对其进行切片等; track
对象的 num 个属性不会“更新” :我希望它们的 num 属性始终为轨道索引+1。
是否有可能实现自动化以及如何实现?
编辑 这些类背后的想法是扩展标准化的 JSPF 对象,目标是 {... playlistdata}
或 {...trackdata}
输出常规 JSPF 对象 - 上面的代码已针对该问题进行了简化。
谢谢!
Let’s say I have a playlist
class like this one:
class playlist{
constructor(urls){
this.tracks=urls;
}
}
I want to use a javascript setter to create an array of track
objects based on the urls input.
class track{
constructor(url,num){
this.url=url;
this.num = num;
}
}
class playlist{
constructor(urls){
this.tracks=urls;
}
//tracks setter
set tracks(urls){
this.tracks = urls.map(function(url,index) {
return new track(url,index+1);
})
}
}
This is fine.
But if I remove some items of the tracks array of the playlist
object, if I slice it, etc; the num properties of the track
objects will not « update » : I want their num property to be always the track index+1.
Is it possible to automate this and how?
EDIT
The idea behind those classes is to extend standardized JSPF objects, in the goal of having {...playlistdata}
or {...trackdata}
output a regular JSPF object - the code above has been simplified for the question.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论