views:

26

answers:

1

Hi,

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

+4  A: 
  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 ) != '') ) {

}
meder
str.length===undefined?
Yosef
Thank you! what about str==null and what about object in first case?
Yosef
Please use the JS console to further test. It's not hard to. I updated with my testing.
meder
meder - +1 Just one thing, and I don't know if this is relevant to the OP's situation, but if you pass an Object or an Array to the second test, it crashes.
patrick dw
i sould also test IE. for object should be isObject(obj)
Yosef
Preferably, comparisons should be made with `===` and `!==`. Hopefully the jQuery API doesn't change to return `undefined` when `$.trim` is given `undefined`, for example.
strager
@patrick dw - you think `typeof` in addition is sufficient?
meder
meder - I honestly don't know. Testing for types in javascript just seems like a big mess. If OP knows that a string is being passed, and just wants to check for its existence, then your answer is the way to go. Would be a shame to have to test for Array and Object and Function (which also crashes). But seems like I've never heard good things about relying on `typeof`.
patrick dw
How do you validate patrick?
Yosef
meder - Actually, using jQuery's method of testing for an Array would perhaps work, but for String instead. `toString.call(obj) === "[object String]";` Seems to work, but would need cross browser testing.
patrick dw
@Yosef - If you are sure you're getting a String or nothing, and just want to make sure it isn't empty, then meder's answer is the way to go. But if you have no idea what will be passed, then additional tests would be needed.
patrick dw