如何使用instanceof检查JSON文件



我有一个带有事件列表的json文件。我想做一个JSON文件的实例,检查是否有任何与Webinar类匹配的事件,然后将其显示到DOM中,但当我使用if或forEach时,我会收到错误或什么都没有。

events.json

[{
"title": "Easter",
"date": "4.5.2021",
"time": "23:00 PM",
"LiveEvent": {
"location": "Ireland",
"adress": "Centrul Vechi 21"
},
"party": {"theme" : " '70s "}
},
{
"title": "Party",
"date": "14.11.2025",
"time": "2:00 PM",
"webinar": {
"webinarTitle": "Com",
"webinarLink": "https://google.com"
},
"party": {"theme" : " '70s "}
},
{
"title": "Birthday",
"date": "30.11.2021",
"time": "7:00 PM",
"webinar": {
"webinarTitle": "Drinks",
"webinarLink": "https://drinks.com"
},
"LiveEvent": {
"location": "Cluj",
"adress": "Centrul Vechi 21"
}
}
]

网络研讨会

class Webinar extends Event {
constructor(title, time, date, webinarTitle, webinarLink){
super(title, date, time)
this.webinarTitle = webinarTitle
this.webinarLink = webinarLink
}
show() {
console.log("This " + this.webinarTitle + " webinar " + "is hosted on " + this.webinarLink)
}
}

JSON是一种将合适的JavaScript值(应用限制(序列化为文本的方法,并通过解析文本来重新创建序列化值来反转过程。JSON不序列化对象的类。

此外,JSON只序列化自己的属性——对象的原型链中没有任何内容被转换为文本。

简而言之,尝试在解析的JSON对象值上使用instanceOf是无效的:任何解析的对象值都是object的实例,而不是其他实例。


潜在解决方案

部分问题可能是class Webinar代码与发布的JSON不匹配。尝试

class Webinar extends Event {
constructor(title, time, date, webinarTitle, webinarLink){
super(title, date, time)
this.webinar = {webinarTitle, webinarLink};  // object property
}
show() {
console.log("This " + this.webinar.webinarTitle + " webinar " + "is hosted on " + this.webinar.webinarLink)
}
}

要扩展Event,然后在对JSON进行编码和解码后,通过检查它是否具有webinar属性来检查它最初是否是Webinar对象:

if( event.webinar) {
// yes it WAS a Webinar object...
}

最后,JSON不序列化函数对象:解码后的Webinar对象将是一个普通对象,其方法继承自Object.prototype。在解码的对象上将不存在诸如show之类的原始方法。

最新更新