myary=new Array();
myary["xx"]=1
if ( myary == "")
alert("myary is null/undefined/nothing")
if (typeof myary =="object")
alert("is obj")
It returns two alerts. But it is not correct as myary did have a value.
change myary["xx"]=1 to myary[0]=1
You will get only the second alert.
try the original script but this time change if(myary == "") to if(myary === "")
again only the second alert is shown.
Checking an array to see if it is empty is kind of awkward. It is not null or "undefined" as you already defined it as array.
Depending on the type of array, the results may be different between using "== " and "===" to compare with "" (empty).
1. If there is no value defined, "==" returns "true" whereas "===" return "false" and the length returned is 0.
2. If there is a valued defined (normal array), both test shows "false". The length returned one or greater.
3. if there is a value defined for associative array, "==" returns "true" whereas "==="return" false. The length returned is always 0.
As you can see, "===" always return false regardless of whether the array has a value. Using this to test whether the array is empty will not be fruitful.
On the other hand "==" actually returns "true" for associative arrays if it has a value. But then if the array has no value, "==" also returns "true".
The only sure way that I know is to use the following method to test
mytruefalse=false
for(x in myary){
mytruefalse=true
break
}
No comments:
Post a Comment