I know you can do the following in javascript to toggle a boolean in a one liner.
我知道你可以在javascript中执行以下操作来切换一个线程中的布尔值。
var toggle = false;
if(true) toggle != toggle;
but is this also possible with a string? i know it can be done by some if statements. But is it possible to do it in a oneliner? something like this:
但这也可以用字符串吗?我知道可以通过一些if语句来完成。但是有可能在oneliner中做到吗?像这样的东西:
var string_toggle = "CAT";
if(true) "CAT" = "ESP" || "ESP" = "CAT";
If it is not clear what i am asking let me know so i can improve the question.
如果不清楚我要问什么让我知道所以我可以改善这个问题。
2 个解决方案
#1
3
You could use the ternary operator.
您可以使用三元运算符。
string_toggle = (string_toggle === "CAT") ? "ESP" : "CAT";
This effectively translates to:
这有效地转化为:
if (string_toggle === "CAT") {
string_toggle = "ESP";
} else {
string_toggle = "CAT";
}
#2
1
If you are a heavy user,why not to make some class?overkill
如果你是一个沉重的用户,为什么不做一些课程?矫枉过正
Here im using this javascript syntax.
我在这里使用这个javascript语法。
You should check ECMAScript 6,you will like it!
你应该检查ECMAScript 6,你会喜欢它!
class ToggleValue {
constructor(value1,value2){
this.values = [value1,value2]
this.pointer = 0
}
toggle(){
this.pointer = +!this.pointer
}
valueOf(){
return this.values[this.pointer]
}
}
var dupaOrGrabowa = new ToggleValue('dupa', 'grabowa')
dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')
dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')
#1
3
You could use the ternary operator.
您可以使用三元运算符。
string_toggle = (string_toggle === "CAT") ? "ESP" : "CAT";
This effectively translates to:
这有效地转化为:
if (string_toggle === "CAT") {
string_toggle = "ESP";
} else {
string_toggle = "CAT";
}
#2
1
If you are a heavy user,why not to make some class?overkill
如果你是一个沉重的用户,为什么不做一些课程?矫枉过正
Here im using this javascript syntax.
我在这里使用这个javascript语法。
You should check ECMAScript 6,you will like it!
你应该检查ECMAScript 6,你会喜欢它!
class ToggleValue {
constructor(value1,value2){
this.values = [value1,value2]
this.pointer = 0
}
toggle(){
this.pointer = +!this.pointer
}
valueOf(){
return this.values[this.pointer]
}
}
var dupaOrGrabowa = new ToggleValue('dupa', 'grabowa')
dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')
dupaOrGrabowa.toggle()
console.log(dupaOrGrabowa + '')