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

javascript - JQuery equivalent to Ruby's a || b - Stack Overflow

programmeradmin2浏览0评论

In Ruby, I can write a || b and the function will choose a if it exists, and if not, b.

How can I do this in JQuery without writing something grossly cumbersome like:

if (a){
  a
} else {
  b
}

Also, does JQuery have an equivalent to Ruby's a ||= b?

In Ruby, I can write a || b and the function will choose a if it exists, and if not, b.

How can I do this in JQuery without writing something grossly cumbersome like:

if (a){
  a
} else {
  b
}

Also, does JQuery have an equivalent to Ruby's a ||= b?

Share Improve this question edited Aug 17, 2011 at 5:04 mu is too short 435k71 gold badges859 silver badges818 bronze badges asked Aug 17, 2011 at 4:48 sscirrussscirrus 56.9k42 gold badges137 silver badges237 bronze badges 2
  • 2 a = a || b; should work. Are you having issues? – hayesgm Commented Aug 17, 2011 at 4:52
  • 1 jQuery doesn't have operators, JavaScript OTOH does. – mu is too short Commented Aug 17, 2011 at 5:04
Add a ment  | 

3 Answers 3

Reset to default 8

jQuery is just a JavaScript library and in JavaScript we have the same.

var c = a || b;

This is because

If the first object is truthy, that gets returned. Otherwise, the second object gets returned.

In JavaScript, a || b evaluates to the first truthy value (or the last value if both are falsy), just as in Ruby. (Remember, jQuery is just a library for JavaScript.)

However, JavaScript has many more falsy (non-truthy values) than Ruby does so care may need to be taken. See Truthy and Falsy: When All is Not Equal in JavaScript.

For instance, in JavaScript: "" || "foo" will result in "foo" although it would have evaluated to "" in Ruby.

Happy coding.


And yes, JavaScript supports x Q= y for all binary operators x = x Q y. An easy way to find out is to just Try It And See :)

var myVariable = myVariable || "Default";
发布评论

评论列表(0)

  1. 暂无评论