Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the best way to check arr, object, string with JQuery undefined + null+ trim(str)!==""?

1. What the best way to check array or object with JQuery undefined + null?

I check array like that:

function f1(arr){
    if(arr!==undefined&&arr!=null){
      //code
    }
}

Is Jquery have better way?


2. What the best way to check String with JQuery trim(str)!==""?

I check String like that:

function f2(str){
    if(str!==undefined&&str!=null&&$.trim(str)!==''){
      //code
    }
}

Is Jquery have better way?

Thanks

like image 520
Ben Avatar asked Dec 31 '25 22:12

Ben


1 Answers

  1. if ( $.isArray( arr ) ) { alert('is array'); }

  2. if ( $.trim(str) != '' ) { alert('is non empty string'); }

Testing:

$.isArray({})
false
$.isArray('')
false
$.isArray(null)
false
$.trim(null)
""
$.trim( undefined )
""

EDIT: You can probably be more explicit in test #2 if you use typeof.

if ( (typeof str === 'string') && ($.trim(str ) != '') ) {

}
like image 53
meder omuraliev Avatar answered Jan 03 '26 14:01

meder omuraliev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!