我正在使用jQuery 1.7.1
我刚开始使用JavaScript三元运算符来替换简单的if/else语句.我在几个地方成功地做到了.当我成功地做出其他工作的时候,当我确信它不会,但我还是试着,我感到很惊讶.
这是原始声明:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
if (IsChecked == true){
removeItem($this);
} else {
addItem($this);
}
}
Run Code Online (Sandbox Code Playgroud)
这是使用三元运算符的相同函数:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
(IsChecked == true) ? removeItem($this) : addItem($this);
}
Run Code Online (Sandbox Code Playgroud)
我很惊讶,因为我看到的所有示例都只是设置这样的变量:
x = (1 < 2) ? true : false;
Run Code Online (Sandbox Code Playgroud)
我的问题是这是否是"正常"使用,它是否适用于大多数JavaScript版本?它会在哪里失败?还有其他不太明显的用途吗?
更新 - 感谢"现实世界"的建议!
我用它作为我的功能:
function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}
Run Code Online (Sandbox Code Playgroud) 这是有效的JavaScript吗?我看到有人在三元运算符条件下使用逗号的示例,并且在我的编辑器中将其标记为错误,并且示例未在Chrome中运行.但是,它确实在Firefox中运行.将所有三元语句转换为if/else语句后,应用程序在Chrome上运行.
a!==b ? (a=1, b=2) : (a=2, b=1)
Run Code Online (Sandbox Code Playgroud)
编辑:
这是代码中的实际语句:
a!==0?b<0?(h=b/a,e=h-1,f=-2*b+2*a*e,i=-2*b+2*a*h,d=2*h*a-2*b-2*a):(h=b/a,e=h+1,f=2*b-2*a*e,i=2*b-2*a*h,d=-2*h*a+2*b):d=h=e=f=i=0
Run Code Online (Sandbox Code Playgroud) 是否可以在三元条件下执行多个操作?类似于以下内容(不起作用):
condition ? () => {
// Perform multiple actions within this delegate function if the condition is true
} : // Perform an action if the condition is false;
Run Code Online (Sandbox Code Playgroud) 我想要一个运行函数的速记如果为true,并且如果为false则运行单独的函数.就像是:
(condition)? function1:function2;
Run Code Online (Sandbox Code Playgroud)