I am using jQuery 1.7.1
I am just starting to use the JavaScript ternary operator to replace simple if/else statements. I have done so successfully in several places. I was surprised when I successfully made something else work when I thought for sure it wouldn't, but I tried anyway.
以下是原始声明:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
if (IsChecked == true){
removeItem($this);
} else {
addItem($this);
}
}
Here's the same function using the ternary operator:
function updateItem() {
$this = $(this);
var IsChecked = $this.hasClass("IsChecked");
(IsChecked == true) ? removeItem($this) : addItem($this);
}
I was surprised because all of the examples I saw being used were merely setting variables like this:
x = (1 < 2) ? true : false;
我的问题是,这是否是"正常"使用,在大多数版本的JavaScript中是否有效?它会在哪里失败?它还有其他不太明显的用途吗?
UPDATE -- Thanks for the "real world" advice!!!
我将此函数用作我的函数:
function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}