I have a variable that I want to check if it is empty. I want to know if I can pass multiple statements if the check is true or false, like:
var checkme = '';
if(checkme == ''){
checkme = 'something new';
do_this();
}else{
checkme = '';
something_else();
}
but using the ?
operator instead. Something like:
checkme == '' ? (checkme = 'something new') (do_this()) :
(checkme = '') (something_else());
I hope you get what I mean by that. I actually got something like that to work, but the console of the browser doesn't like it. Is there a way to properly do this, or do I need to write out the if...else
statement?
I have a variable that I want to check if it is empty. I want to know if I can pass multiple statements if the check is true or false, like:
var checkme = '';
if(checkme == ''){
checkme = 'something new';
do_this();
}else{
checkme = '';
something_else();
}
but using the ?
operator instead. Something like:
checkme == '' ? (checkme = 'something new') (do_this()) :
(checkme = '') (something_else());
I hope you get what I mean by that. I actually got something like that to work, but the console of the browser doesn't like it. Is there a way to properly do this, or do I need to write out the if...else
statement?
-
Use
&&
or||
in between two conditions – Tushar Commented Dec 3, 2015 at 11:22 -
What's the problem with
if {...} else {...}
? – Andreas Commented Dec 3, 2015 at 11:24 -
1
The ternary operator is for assignment, please don't use it to execute code.
if-else
is the right tool for that. – Sulthan Commented Dec 3, 2015 at 11:24 - I couldn't find anything that told me not to, so I was curious. Thanks! – Cycling Paper Commented Dec 3, 2015 at 11:27
4 Answers
Reset to default 5Yeap you can do. Example below & fiddle:
var a = true;
a ? (console.log(1 + 1),console.log(2+2)):
(console.log(false), console.log(false))
your case :
checkme == '' ? (checkme = 'something new', do_this()) :
(checkme = '', something_else());
Just separate your mands with a. Mozilla Doc
Thanks.
checkme == '' ? ((checkme = 'something new') && (do_this())) :
((checkme = '') && (something_else()));
as Tushar said
It works even shorter, if the position of the function call is not important.
checkme = checkme ? (something_else(), '') : (do_this(), 'something new');
if you really need to have fun doin it like that:
window[checkme == '' ? (checkme = 'something new') && 'do_this' : (checkme = '') && 'something_else']()
this will look for the function by string and execute it and also assign the new value
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744665773a4586739.html
评论列表(0条)