Monday, May 6, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  55] [ 2]  / answers: 1 / hits: 54186  / 16 Years ago, wed, march 4, 2009, 12:00:00

I want to test whether a JavaScript variable has a value.



var splitarr =  mystring.split(   );
aparam = splitarr [0]
anotherparam = splitarr [1]
//.... etc


However the string might not have enough entries so later I want to test it.



if ( anotherparm /* contains a value */ )


How do I do this?


More From » javascript

 Answers
25

In general it's sort of a gray area... what do you mean by has a value? The values null and undefined are legitimate values you can assign to a variable...



The String function split() always returns an array so use the length property of the result to figure out which indices are present. Indices out of range will have the value undefined.



But technically (outside the context of String.split()) you could do this:



js>z = ['a','b','c',undefined,null,1,2,3]
a,b,c,,,1,2,3
js>typeof z[3]
undefined
js>z[3] === undefined
true
js>z[3] === null
false
js>typeof z[4]
object
js>z[4] === undefined
false
js>z[4] === null
true

[#99891] Thursday, February 26, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
whitney

Total Points: 642
Total Questions: 110
Total Answers: 98

Location: Solomon Islands
Member since Mon, Jun 20, 2022
2 Years ago
;