最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this ternary operator invalid in JS - Stack Overflow

programmeradmin5浏览0评论
​var truth = true;
(truth) ? console.log('It is true') : throw new Error('It is not true');​​​​​​​​​​​​​​​

Do ternary operators only accept specific types of objects?

​var truth = true;
(truth) ? console.log('It is true') : throw new Error('It is not true');​​​​​​​​​​​​​​​

Do ternary operators only accept specific types of objects?

Share Improve this question asked Nov 21, 2012 at 22:27 FreddieFreddie 7412 gold badges10 silver badges23 bronze badges 1
  • You could make a function: function _throw(msg) { throw new Error(msg); } then use it in the conditional operator: truth ? console.log("true") : _throw("It is not true"); – I Hate Lazy Commented Nov 21, 2012 at 22:33
Add a ment  | 

3 Answers 3

Reset to default 18

javascript distinguishes between statements and expressions. The ternary operator only handles expressions; throw is a statement.

It does work, but the problem is the throw statement in your "else" branch.

Use

(truth) ? console.log('It is true') : (function(){throw 'It is not true'}());

The conditional operator, like all other operators, can only be used with expressions.

throw x; is a statement, not an expression.

发布评论

评论列表(0)

  1. 暂无评论