我需要根据创建对象时发送的参数值,设置两个标记canPlayLive
和isSubscribed
到true
或false
。
基本上,当null
undefined
''
通过时,我想要false
上的标记,否则true
上的标记。
使用以下代码标记始终位于true
。
我在这里做错了什么?
function MyStation(id, chId, name, hdImg, subscribedFlag, liveEntryId, liveUrl, timeLists) {
this.id = id;
this.dataId = chId;
this.name = name;
this.imageUrl = hdImg;
this.subscribedFlag = subscribedFlag;
this.liveEntryId = liveEntryId === null || undefined || '' ? null : liveEntryId;
this.liveUrl = liveUrl === null || undefined || '' ? null : liveUrl;
this.timeLists = timeLists;
this.canPlayLive = this.liveUrl === null || undefined || '' ? false : true;
this.isSubscribed = subscribedFlag == 0 ? false : true;
}
var test = new MyStation(
0,
'x123',
'foo',
'url',
0,
null,
'',
[]
);
console.log(test);
答案 0 :(得分:1)
由于canPlayLive依赖于liveUrl,因此您应该按如下方式编写代码:
if (liveUrl ) {
this.liveUrl = (liveUrl == '') ? null : liveUrl;
}
<强>说明:强> 当参数liveUrl为null或未定义时,结果将始终为false,否则为true。 既然你想要也将空字符串视为null,我们需要第二个条件。
当this.liveUrl具有正确的值时,让我们转到canPlayLive变量:
this.canPlayLive = this.liveUrl || false;
<强>解释强>: 当this.liveUrl为null时,它被视为false,因此结果将为false。
当this.liveUrl为非null时,它被视为true,因此true或false将始终为true。
答案 1 :(得分:0)
我能够使用!liveUrl
代替''
来解决我的问题。
function MyStation(id, chId, name, hdImg, subscribedFlag, liveEntryId, liveUrl, timeLists) {
this.id = id;
this.dataId = chId;
this.name = name;
this.imageUrl = hdImg;
this.subscribedFlag = subscribedFlag;
this.liveEntryId = liveEntryId === null || undefined || !liveEntryId ? null : liveEntryId;
this.liveUrl = liveUrl === null || undefined || !liveUrl ? null : liveUrl;
this.timeLists = timeLists;
this.canPlayLive = this.liveUrl === null || undefined || !liveUrl ? false : true;
this.isSubscribed = subscribedFlag == 0 ? false : true;
}