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

1. What is the best way to test an array or object using jQuery undefined + null?

I check the array as follows:

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

Does jquery have a better way?


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

I check String as follows:

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

Does jquery have a better way?

thank

+3
source share
1 answer
  • if ( $.isArray( arr ) ) { alert('is array'); }

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

Testing:

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

EDIT . Perhaps you can be more explicit in test # 2 if you use typeof.

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

}
+4
source

Source: https://habr.com/ru/post/1757585/


All Articles