Javascript三元运算符,其他为空 [英] Javascript Ternary operator with empty else

查看:1326
本文介绍了Javascript三元运算符,其他为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以下if-else转换为javascript中的三元运算符表示,如下所示

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}

但当我这样做时:

(t==2)?(alert("1")):();

Chrome会抛出一个SyntaxError。

Chrome throws a SyntaxError.

我的问题是 -
如何使用空的else分支在javascript中使用三元运算符 - 即:之后的部分。
另外,这是允许的 - 使用javascript中的三元运算符来执行语句 - 不执行赋值。

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.

另外:上面的代码只是一个基本情况。我实际上试图将页面的所有DOM元素作为一个数组(称为all2),然后只有当它们具有非null类名时才将这些元素添加到另一个数组(仅限于调用)。这是我的代码:

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"))) : (); }); 

如果我将第三个操作数留空,则会引发语法错误。传递null工作

If I leave the third operand blank, it throws a syntax error. Passing a null works

推荐答案

在评论中回答你的真实问题:

Answer to your real question in the comments:

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

这篇关于Javascript三元运算符,其他为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆