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

…衆ロ難τιáo~ 提交于 2019-12-17 19:05:57

问题


Say I have a function like so:

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

And say I call foo(1), how do I know it returns an array or not?


回答1:


I use this function:

function isArray(obj) {
  return Object.prototype.toString.call(obj) === '[object Array]';
}

Is the way that jQuery.isArray is implemented.

Check this article:

  • isArray: Why is it so bloody hard to get right?



回答2:


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.




回答3:


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; }
}



回答4:


As of ES5 there is isArray.

Array.isArray([])  // true



回答5:


To make your solution more general, you may not care whether it is actually an Array object. For example, document.getElementsByName() returns an object that "acts like" an array. "Array compliance" can be assumed if the object has a "length" property.

function is_array_compliant(obj){
    return obj && typeof obj.length != 'undefined';
}


来源:https://stackoverflow.com/questions/1202841/what-is-the-best-way-to-check-if-an-object-is-an-array-or-not-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!