有没有办法使用一段 JavaScript 在两个字符串之间切换?
我想
if(something.val() == 'string1')
{
something.val('string2');
}
else if(something.val() == 'string2')
{
something.val('string1')
}
用一行代码做类似 But 的事情。我不太记得它是怎么做的,但它涉及问号和冒号......
I want to do something like
if(something.val() == 'string1')
{
something.val('string2');
}
else if(something.val() == 'string2')
{
something.val('string1')
}
But in one line of code. I can't quite remember how it's done, but it involves question marks and colons...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
尝试:
称为三元表达式。
Try:
It is called a ternary expression.
看吧,没有三元运算符!
以下之所以有效,是因为 Javascript 短路了布尔表达式。
如果
something == string1
,则评估string2
——因为string2
是一个truthy值,并且下一个表达式涉及OR 运算无需继续。停止并返回string2
。如果
something !== string1
那么它将跳过下一个操作数,因为如果它为 false,则评估下一个操作数(使用 AND)是没有意义的。它将“跳转”到 OR 运算并返回string1
。如果您希望完成分配:
但是最终,我最终会使用三元运算符,因为其他程序员可能不清楚此解决方案。如果您来自 Java 或其他语言,由于所有布尔运算符,您可能期望该函数返回布尔值。
Look ma, no ternary operator!
The following works because Javascript short circuits boolean expressions.
If
something == string1
then evaluatestring2
-- sincestring2
is a truthy value and the next expression involves the OR operation there is no need to continue. Stop and returnstring2
.If
something !== string1
then it will skip the next operand because if it is false, there is no point in evaluating the next operand (with AND). It will "jump" to the OR operation and returnstring1
.If you want the assignment done:
In the end however, I would end up using the ternary operator because this solution might be unclear to other programmers. If you come from Java or other languages, you may expect the function to return a boolean because of all the boolean operators.
使用对象属性的另一种方法:
如问题所示:
Another way to do it using object properties:
As in the question:
如何将 @Daniel 的代码与 jquery 函数一起使用:
How about using @Daniel's code along with a jquery function:
不过,使用三元运算符的解决方案是最具可读性的,您也可以使用 Lodash 中的 xor:
对于您的具体情况:
参考:https://lodash.com/docs/4.17.10#xor
Though, the solutions with a ternary operator are the most readable, you could also use xor from Lodash:
For your specific case:
Ref: https://lodash.com/docs/4.17.10#xor
您的意思是使用三元运算符:
You mean to use the ternary operator:
从 jQuery 1.4 开始,你可以这样做:
As of jQuery 1.4, you can do this:
或为了澄清
or for clarification
在类似的情况下我的方法是这样的:
My way was this in a similar situation: