[Reprinted] tips for using ternary operators-Javascript

Source: Internet
Author: User
Document directory
  • Common usage
  • Usage with a little cleverness
  • Even more abnormal.
  • Please try again
  • Therefore, it is the complete body of the teacher.
  • Situations to be avoided as much as possible

Original post address: http://qilei.org/201101/ternary-tip-for-javascript/comment-page-1/

When I find that the code is too much to write, I will unconsciously Replace the if else with three elements, just without making the code more concise and incisive, of course, some people say that the use of three yuan can make you feel a climax. I recently felt this way when I was writing JavaScript, And I collected some tips and shared them.
Please skip the following section, and the big bird will help you correct it ^__ ^
==== Popularity ====

Expression (expr1 )? (Expr2): (expr3) when the value of expr1 is true, the value is expr2, and when the value of expr1 is false, the value is expr3.

================

Common usage

When you find that you often use if else

If (baichunge | baiqiudi) {No subject;} else {Door to door ;}

The three-element representation is

Baichun brother | Baishi test emperor? No mounting: Door mounting

The code is brilliant.

Such if else judgments are often made in daily use. In particular, it is more harmonious to use the ternary element when there are many nesting elements, which can make your code look more fresh and have a clear structure.

Usage with a little cleverness

Through constant changes, many ternary usage can be derived. The following jquery code

flag ? $('body').addClass('hover') : $('body').removeClass('hover') ;
Even more abnormal.
$('.item')[ flag ? 'addClass' : 'removeClass']('hover')

The above code looks confusing. When flag is set to true, the Code becomes the following code:

$('.item')['addClass']('hover')

This statement is equivalent.

$('.item').addClass('hover')

For more information, see Haomei's article.
// At first, I had never understood why I could write it like this. After communication, I suddenly realized, haha.

Please try again

You can call the desired function as needed to handle more things.

function a(){      do something}function b(){      do something}flag ? a() : b();
Therefore, it is the complete body of the teacher.

So in this case, two buttons act forward and backward. The operation functions are similar.

    var action_turn = function(e, type){        var self = $(e).closest('li');        var target = self[type === 'prev' ? 'prev' : 'next']();        target.addClass('has-img');        self.removeClass('has-img')    }    var btn_next = $('#item-photo-panel a.next')    btn_next.click(function(){        action_turn(this, 'next');        return false;    });    var btn_prev = $('#item-photo-panel a.prev')    btn_prev.click(function(){        action_turn(this, 'prev');        return false;    });
Situations to be avoided as much as possible
alert( true ? 'true' : false ? 't' : 'f' )

I mean try to avoid the three elements nested above, because in JS, the statements are from right to left, and the above Code is equivalent

alert( true ? 'true' : ( false ? 't' : 'f' ) )

For example, the results in PHP are completely different, and the left-side priority is given when the three elements are nested.

Echo (true? 'True': false )? 'T': 'F') // PHP

Tip:
In addition, we found that the Trielement in PHP had such a prompt.

Note: The ternary operator is a statement. Therefore, the result is not a variable but a statement. It is important to return a variable through reference. Return $ Var = 42? $ A: $ B; will not work, and a warning will be issued for future PHP versions.

However, after testing, it is found that the above practices in javascript can work, probably because JS is relatively Bt and its degree of rigor is not as big as PHP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.