Checking if a variable is an array



  • var noteLetters = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
    Console.print("INFO: " + (noteLetters.constructor === Array));
    

    The above code prints 0 (or undefined if cast to string). Any idea where I'm going wrong?

    I've also tried the following but HISE doesn't seem to like it.

    Console.print("INFO: " + (noteLetters instanceof Array));
    

    I've also tried the standard .isArray which didn't work, I tried it as a function too but HISE didn't recognise it. I also tried declaring the array with the "new Array" method.



  • That's the part of the Javascript engine which is not fully standard compliant. I actually never used the new keyword. It also doesn't support prototypes (which I am assuming the .constructor property is).

    But there are multiple ways to get to your solution. The fastest would be to check if the variable has a property "length", which is

    var array = ["C", 1, 2];
    var x = 24;
    var empty = [];
    
    var object = {};
    
    object.property = 12;
    
    function isArray(variable)
    {
    	return !(variable.length === undefined); // === operator to catch empty arrays
    };
    
    Console.print(isArray(x)); // 0
    Console.print(isArray(array)); // 1
    Console.print(isArray(empty)); // 1
    Console.print(isArray(object)); // 0
    
    


  • I thought about that but strings also have a length property so I would need an extra check too make sure it wasn't a string. I'll make a little function that does both checks thanks for the quick response



  • Oops, I forgot about strings in my little test suite

    function isArray(variable)
    {
       return !(variable.length === undefined) && typeof(variable) != "string";
    };
    
    

    This should do the trick…


 

1
Online

353
Users

1.1k
Topics

7.6k
Posts