best way to test if a variable is an array

Possible Duplicate:
How to detect if a variable is an array

When I need to test if variable is an array (for example input argument in a function that could be object or array) I usually use this piece of code

typeof(myVar) === 'object' && myVar.length !== undefined;

Is this the correct way or is there a more efficient way, considering that even if myVar instanceof Array is faster it should be avoided due to iframe problem?


Array.isArray现在可用于ECMAScript 5,因此您可以将它与polyfill一起用于旧版浏览器:

if(!Array.isArray) {
  Array.isArray = function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
  };
}

Array.isArray(myVar);

在我看来,“iframe问题”可以简单地通过不使用同一个名称来完成,在我看来,这并不难。但是,我从来没有必要断言某件事是否是阵列...


If you are already using jQuery within your code, you may use jQuery.isArray(). Here is the documentation:

http://api.jquery.com/jQuery.isArray/

链接地址: http://www.djcxy.com/p/19318.html

上一篇: 如何通过两个键订购JSON对象?

下一篇: 测试变量是否为数组的最佳方法