带函数的JavaScript三元运算符示例 [英] JavaScript ternary operator example with functions
问题描述
我正在使用jQuery 1.7.1
I am using jQuery 1.7.1
我刚开始使用JavaScript三元运算符来替换简单的if / else语句。我在几个地方成功地做到了。当我成功地做出其他工作的时候,当我确定不会这样做时,我很惊讶,但我还是尝试过。
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版本?它会在哪里失败?还有其他不太明显的用途吗?
My question is whether this is "normal" use and will it work in most versions of JavaScript? Where will it fail? Are there other less obvious uses for it?
更新 - 感谢真实世界的建议!!!
我使用它作为我的函数:
I am using this as my function:
function updateItem() {
$this = $(this);
$this.hasClass("IsChecked") ? removeItem($this) : addItem($this);
}
推荐答案
嘿,有一些漂亮的在你的问题中激动地使用三元语法;我最喜欢最后一个......
Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...
x = (1 < 2) ? true : false;
这里使用三元是完全不可能的 - 你可以简单地写一下
The use of ternary here is totally uncessesary - you could simply write
x = (1 < 2);
同样,三元语句的condition元素总是被评估为布尔值,因此你可以表达:
Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, therefore you can express:
(IsChecked == true) ? removeItem($this) : addItem($this);
简单如下:
(IsChecked) ? removeItem($this) : addItem($this);
事实上,我还会删除 IsChecked
暂时离开你:
Infact, I would also remove the IsChecked
temporary as well which leaves you with:
($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);
至于这是可接受的语法,它肯定是!这是将四行代码减少为一行而不影响可读性的好方法。我给你的唯一建议是避免在同一行上嵌套多个三元语句(这就是疯狂!)
As for wether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)
这篇关于带函数的JavaScript三元运算符示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!