By using the prototype name string instead of the typeof function we can get a more accurate check of the variable type. For instance:
variable["__proto__"]["constructor"]["name"]
var Array = []; //returns "Array"
var Object = {}; //returns "Object"
var Array = new Array(); // returns "Array"
With this we no longer have to have an additional logical statement to check if our our objects are arrays in disguise or actually an object.
Using a reverse while loop means that array.length doesn't have to be evaluated each increment and reduces character wastage. It does make the logic more confusing to write in controlled sequential cases, but in this case is fine
var i=arr.length;
while(i--){switch(arr[i].__proto__.constructor.name;){
case'Object':{attr = arr[i]; break;}
case'String':{text = arr[i]; break;}
case'Array':{child = arr[i]; break;}
default:{break;}}}
or a more readable version:
var myArray = [150,"Entry",{"x":15,"y":26}]; //input array
var index = myArray.length; //evaluate the length of the array
while(index--) //decrement the index while it's greater than 0
{
var type = myArray[index]["__proto__"]["constructor"]["name"];//what type is this variable
switch(type)
{
case:'Object': //if object
{
attr = myArray[index]; //set attribute to field
break;
}
case:'String': //if string
{
text = myArray[index]; //set text to field
break;
}
case:'Array': //if array
{
child = myArray[index]; //set child to field
break;
}
default:
{
console.log("Error, entry does not match requested types");
break;
}
}
}
Using a quasi-referance object array to start with would be a lot more obvious way to do this though, it seems a rather backwards way to extract relevant information from an unsorted array than to just pick items out of your choosing.
var myArray =
{
"values":[150,160,170],
"name":"entry",
"coord":{"x":15,"y":26}
}
//then
attr = myArray["coord"];
text = myArray["name"];
child = myArray["values"];
//or
attr = myArray.coord;
text = myArray.name;
child = myArray.values;
Array.isArray
will also work with non-objects. You don't need to check if it's an object. – Prinzhorn 8 hours agox
variable altogether; sincearr.length
is short and clear enough by itself. – Zar 44 mins ago