I'm trying to convert the following if-else to it's ternary operator representation in javascript as follows
var x = 2;
if (x === 2) {alert("2");}
else
{ //do nothing}
But when I do this:
(t==2)?(alert("1")):();
Chrome throws a SyntaxError.
My question is -
How to have a ternary operator in javascript with an empty "else" branch - i.e the part that comes after ":".
Also, is this allowed- using a ternary operator in javascript to execute statements - NOT do assignment.
Also: the above code was just a base case. I'm actually trying to get all the DOM elements of the page as an array (called all2) and then add only those elements to another array (called only) only if they have non-null class names. Here is my code:
all2.forEach(function(e){ e.getAttribute("class") ? (only.push(e.getAttribute("class"))) : (); });
If I leave the third operand blank, it throws a syntax error. Passing a null works
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…