How do you use the ? : (conditional) operator in JavaScript?

前端 未结 18 1673
感动是毒
感动是毒 2020-11-21 05:48

In simple words, what is the ?: (conditional, "ternary") operator and how can I use it?

18条回答
  •  Happy的楠姐
    2020-11-21 06:07

    We can use with Jquery as well as length as below example :

    Suppose we have GuarantorName textbox which has value and want to get firstname and lastname- it may be null. So rathar than

            var gnamesplit = $("#txtGuarantorName").val().split(" ");
            var gLastName = "";
            var gFirstName = "";
            if(gnamesplit.length > 0 ){
               gLastName  = gnamesplit[0];        
            }
            if(gnamesplit.length > 1 ){
               gFirstName = gnamesplit[1];        
            }
    

    We can use below code with Jquery with minimum code

        
    
        var gnamesplit = $("#txtGuarantorName").val().split(" ");
        var gLastName = gnamesplit.length > 0  ? gnamesplit[0] : "";
        var gFirstName =  gnamesplit.length > 1  ? gnamesplit[1] : "";
        $("#txtLastName").val(gLastName);
        $("#txtFirstName").val(gFirstName);
        
        
    
    
    
    Guarantor Name:


    First Name: Last Name:

提交回复
热议问题