Javascript 在构造函数中传递参数时无法设置对象的属性
我需要根据创建对象时发送的参数值,设置两个标志Javascript 在构造函数中传递参数时无法设置对象的属性,javascript,javascript-objects,Javascript,Javascript Objects,我需要根据创建对象时发送的参数值,设置两个标志canPlayLive和isSubscribed到true或false 基本上,当null未定义的'被传递时,我希望在false上标记,否则在true上标记 使用以下代码标志时,将始终启用true 我做错了什么 function MyStation(id, chId, name, hdImg, subscribedFlag, liveEntryId, liveUrl, timeLists) { this.id = id; this.d
canPlayLive
和isSubscribed
到true
或false
基本上,当null
未定义的'
被传递时,我希望在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);
由于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。我能够使用解决我的问题!liveUrl
而不是'
阅读JS语法。您需要执行liveEntryId===null | | liveEntryId===undefined | |或liveEntryId===''
,但不会执行!liveEntryId
也能正常工作?同意-!liveEntryId将覆盖所有基础。!如果公平地说,liveEntryId等于0
或NaN
,则会错误地导致true
,liveEntryId===null | | liveEntryId==undefined | |或liveEntryId=='
@sahbeewah-不正确:0
和NaN
都是错误的,即,强制为布尔状态时解析为false。有用:
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;
}