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

后端 未结 5 648
粉色の甜心
粉色の甜心 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:38

    if(foo(1) instanceof Array)
        // You have an Array
    else
        // You don't
    

    Update: I have to respond to the comments made below, because people are still claiming that this won't work without trying it for themselves...

    For some other objects this technique does not work (e.g. "" instanceof String == false), but this works for Array. I tested it in IE6, IE8, FF, Chrome and Safari. Try it and see for yourself before commenting below.

提交回复
热议问题