I’m honestly tearing out what little hair I have left at the moment. I can’t seem to write a script or find a script that can perform an isset() or is_array() with out throwing Javascript errors in Firefox. I just keep thinking… surely someone out there must know how to do this. How can modern Javascript not have this kind of functionality built in.
Here’s the angle I’m coming from.
function is_array(variable)
{
if( typeof(variable) == 'undefined' )
{
return false;
} else {
//If this variable is an object?
if ( typeof(variable) == 'object' )
{
if(variable.length)
{
return true;
} else { //The length was zero or null
return false;
}
} else { //It was not an object
return false;
}
}
}
if(is_array(nothing))
{
alert('Yes - an array');
} else {
alert('Not - an array');
}
Instead of getting “Yes - an array” or “Not - an array” I get some errors in the Firefox error console.
The problem here is that you’re trying to apply what you know from PHP on to JavaScript. Things don’t work well that way.
Write in the language that you’re writing in, is the maxim.
In this case, Array.isArray exists in JavaScript 1.8.5 and onwards.
You would do well though to investigate the compatibility code from the Array.isArray documentation page, so that you can use the same technique in browsers that don’t yet support JavaScript 1.8.5
It happens because you are trying to use the var “nothing” but it isn’t defined anywhere.
Try
var nothing = undefined;
if(is_array(nothing)) {
//etc...
Or simply calling it without a parameter will render variable as undefined.
Like Paul said, you’re trying to apply some PHP principles here, it might be worth checking out PHP JS which is an attempt to port a lot of PHP functions to JavaScript
Yea, I get that now. I’m trying to emulate how PHP does this. In PHP with most versions you simply just go is_array(something). If it is an array you get true in return, if it’s entirely “anything” else you get false, which is what I was expecting I could do with JS. I’m just gotta rethink my strategy here.
All you really need is for nothing to be defined before you use it. As a general rule you would declare any variables before you use them first, so you would avoid the reference error.
i.e.
var nothing = null;
var something = [1, 2, 3];
Array.isArray(someUndefinedVariable) // Will fail, 'someUndefinedVariable' hasn't been defined yet.
Array.isArray(nothing); // This will work and return false.
Array.isArray(something); // This will work and return true.
Well, the OP does use typeof in his code
Alas, [I]typeof[/I] will just say that an array is of the object type.