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

javascript - Jslint use '||' operator instead of conditional operator - Stack Overflow

programmeradmin3浏览0评论

I have jslint plaining me to use || operator for below code,

query = ['browser' + (ieVersion ? ieVersion : 'UNKNOWN')]

I tried using || operator but that ends up in wrong result,

query = ['browser' + ieVersion || 'UNKNOWN'] 
// => ['browserundefined']

I have jslint plaining me to use || operator for below code,

query = ['browser' + (ieVersion ? ieVersion : 'UNKNOWN')]

I tried using || operator but that ends up in wrong result,

query = ['browser' + ieVersion || 'UNKNOWN'] 
// => ['browserundefined']
Share Improve this question edited Dec 18, 2012 at 18:01 Mahesh Kulkarni asked Dec 18, 2012 at 17:36 Mahesh KulkarniMahesh Kulkarni 3073 silver badges11 bronze badges 3
  • Sorry my bad, I did try with parentheses. Will update the question now – Mahesh Kulkarni Commented Dec 18, 2012 at 17:55
  • Um. But it works with parens, as in the answer you accepted. – Dave Newton Commented Dec 18, 2012 at 18:01
  • Edit: I screwed. I actually din't use brackets. I will always worry about precedence from now on. – Mahesh Kulkarni Commented Dec 18, 2012 at 18:01
Add a ment  | 

3 Answers 3

Reset to default 6

Operator precedence is wrong, try this:

query = ['browser' + (ieVersion || 'UNKNOWN')]

without extra parentheses + operator is stronger and JavaScript engine evaluates it as:

query = [('browser' + ieVersion) || 'UNKNOWN']

Notice that 'browser' + ieVersion is never falsy so you'll never see 'UNKNOWN'.

brackets?

query = ['browser' + (ieVersion || 'UNKNOWN')]

You need to wrap the expression in parentheses:

query = ['browser' + (ieVersion || 'UNKNOWN')]
发布评论

评论列表(0)

  1. 暂无评论