Javascript does not provide a function to recognize if a variable is an array or not; you can make a “typeof” of the variable however u’ll get an ‘object’ datatype, as in the following code
[sourcecode language=”javascript”]
var myarray = [1, 2, 3];
var myobject = { key: ‘value’ };
alert(typeof myarray); //return ‘object’
alert(typeof myobject); //return ‘object’
[/sourcecode]
to recognize a data type ‘object’ from ‘array’, you need a specialized function like this…
[sourcecode language=”javascript”]
function isArray(value){
var b = typeof value;
if(b === ‘object’){
if(value){
b = (typeof value.length === ‘number’ &&
!(value.propertyIsEnumerable(‘length’)) &&
typeof value.splice === ‘function’) ? true : false;
}else{
b = false;
};
};
return b;
};
var myarray = [1, 2, 3];
var myobject = { key: ‘value’ };
alert(isArray(myarray)); //return true
alert(isArray(myobject)); //return false
[/sourcecode]
Good work!
Max 🙂
Leave a Reply