简体   繁体   中英

Differentiate between array of arrays and array of values

I have two arrays:

var firstarray = [123, 13, 34, 12, 63, 63];

var secondarray = [[10,20,10], [122, 123, 53], [542, 234, 12, 331]];

I need to have a function that works something like this:

function checkArray(array){
    //if array contains multiple arrays, return true
    //if the array contains only values, return false
}

The number of arrays inside secondarray always varies.

Hint: Loop on the first array and determine if one of the object you're reading is an array.

Here is a function that could help you :

function is_array(input){
    return typeof(input)=='object'&&(input instanceof Array);
}

In modern Javascript:

 myAry.every(Array.isArray) // returns true if all elements of myAry are arrays

References (and replacements for older browsers):

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray

The main problem to this is that in JavaScript typeof anArrayVariable returns object as does typeof aRealObject - so there's no easy way to distinguish them.

jQuery fixes this to some extent with a method $.isArray() which correctly returns true for an array and false for an object, a number, a string or a boolean.

So, using jQuery this becomes as easy as:

function checkArray(array){
    //if array contains multiple arrays, return true
    //if the array contains only values, return false

    for(var i=0;i<array.length;i++){
      if($.isArray(array[i]))   
          return true;
    }
    return false;
}

I suggest you could take a look at the source for that method in jQuery and implement this same idea in vanilla javascript.

Check the type of the first element in the array:

function checkArray(list) {
  return typeof(list[0]) == "object";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM