What is the best way to check if an object is an array or not in Javascript?

后端 未结 5 657
粉色の甜心
粉色の甜心 2020-12-09 23:04

Say I have a function like so:

function foo(bar) {
    if (bar > 1) {
       return [1,2,3];
    } else {
       return 1;
    }
}

And s

5条回答
  •  悲哀的现实
    2020-12-09 23:14

    Here is one very reliable way, take from Javascript: the good parts, published by O'Reilly:

    if (my_value && typeof my_value === 'object' &&  typeof my_value.length === 'number' &&
    !(my_value.propertyIsEnumerable('length')) { // my_value is truly an array! }
    

    I would suggest wrapping it in your own function:

    function isarray(my_value) {
    
        if (my_value && typeof my_value === 'object' &&  typeof my_value.length === 'number' &&
            !(my_value.propertyIsEnumerable('length')) 
             { return true; }
        else { return false; }
    }
    

提交回复
热议问题