我是使用jquery的新手,我想问一下你怎么称呼这种语句我要在里面添加一个If语句
顺便说一句。此处的“读取”为布尔值,我希望更改Read == true
read: 'read'
,如果为false,则为unread: 'unread'
这是我的原始代码:
var options = { id: ID,
read: Read == true ? 'unread' : 'read',
category: "projects",
message: Message
};
和我的审判但没有成功:
var options = {
if(Read == true) {
id: ID,
read: 'read',
category: "projects",
message: Message
}
else {
id: ID,
unread: 'unread',
category: "projects",
message: Message
}
};
在expected identifier or string
字
if
先谢谢
答案 0 :(得分:2)
使用三元运算符:
(expression_to_test) ? (value_if_true) : (value_if_false)
var options =
(Read == true) ? {
id: ID,
read: 'read',
category: "projects",
message: Message
}
: {
id: ID,
unread: 'unread',
category: "projects",
message: Message
}
;
<强>注意强>
花括号{}不是三元运算符语法的一部分。它们在这里用于创建内联对象。在上面的代码中,如果Read == true
,则运算符返回由第一个花括号创建的对象。
答案 1 :(得分:0)
如果Read是布尔值,则:
var Read = false;
var options = {
id: 12,
read: Read ? 'unread' : 'read',
category: "projects",
message: 'msg'
};
console.log(options); // {id: 12, read: "read", category: "projects", message: "msg"}
Read = true;
options = {
id: 12,
read: Read ? 'unread' : 'read',
category: "projects",
message: 'msg'
};
console.log(options); // {id: 12, read: "unread", category: "projects", message: "msg"}
但在我看来,Read不是布尔值,因为如果是,那么你原来的代码就可以了:
var Read = false;
var options = {
id: 12,
read: Read == true ? 'unread' : 'read',
category: "projects",
message: 'msg'
};
console.log(options); // {id: 12, read: "read", category: "projects", message: "msg"}
Read = true;
options = {
id: 12,
read: Read == true ? 'unread' : 'read',
category: "projects",
message: 'msg'
};
console.log(options); // {id: 12, read: "unread", category: "projects", message: "msg"}
答案 2 :(得分:0)
使用像Claudix所说的三元运算符,但是;
如果没有结构差异,请勿更改“选项的结构”。区别在于“是否读取”=&gt;这应该由选项上的单个属性表示。
var options = {
id: ID,
read: Read,
category: "projects",
message: Message
};
代码中的任何地方,如果要检查它是否已被读取,您现在可以执行“简单”。
if (options.read) {
// it was read
} else {
// it was not read yet.
}
防止需要“未读”属性和“读/未读”字符串比较。