检测传递的参数是否为数组?使用Javascript

Ale*_*lex 48 javascript arrays arguments parameter-passing

可能重复:
如何检测变量是否为数组

我有一个简单的问题:

如何检测传递给我的javascript函数的参数是否为数组?我不相信我可以测试:

if (typeof paramThatCouldBeArray == 'array') 
Run Code Online (Sandbox Code Playgroud)

那有可能吗?

我该怎么办?

提前致谢.

Cas*_*Chu 67

if (param instanceof Array)
    ...
Run Code Online (Sandbox Code Playgroud)

编辑.截至2016年,有一个现成的方法可以捕获更多的极端情况Array.isArray,使用如下:

if (Array.isArray(param))
    ...
Run Code Online (Sandbox Code Playgroud)

  • 适用于大多数情况,但它不适用于跨框架环境,请看一下[文章](http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust- IsArray的/). (8认同)
  • `!! param.shift`在执行速度方面会更快.http://jsperf.com/instanceof-vs-method-detect (3认同)
  • 如果您确定不会跨帧操作(通常是这种情况),那么请使用构造函数方法.性能比较:http://jsperf.com/detecting-arrays-new (2认同)

Jam*_*ate 18

这是jQuery 1.4.2使用的方法:

var toString = param.prototype.toString;
var isArray = function(obj) {
        return toString.call(obj) === "[object Array]";
    }
Run Code Online (Sandbox Code Playgroud)

  • 如果param是字符串"[object Array]"怎么办?我认为在字符串上调用toString会返回字符串本身 (3认同)

Ger*_*son 5

我在这里找到了这个:

function isArray(obj) {
    return obj.constructor == Array; 
}
Run Code Online (Sandbox Code Playgroud)

也是这一个

function isArray(obj) {
    return (obj.constructor.toString().indexOf(”Array”) != -1);
}
Run Code Online (Sandbox Code Playgroud)