Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

if statement - Javascript Ternary operator with empty else

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Answer to your real question in the comments:

all2.forEach(function (e) {
    e.getAttribute("class") && only.push(e.getAttribute("class"));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...