
如何判断javascript中的变量是否为数组?
通过下面方法进行检测,如果是数组,则返回true,如果不是数组,则返回false
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
测试:
var a1 = [1,2,3];
var a2=new Array("a","b");
var a3={a:1};
alert(isArray(a1));//true
alert(isArray(a2));//true
alert(isArray(a3));//false
补充:
根据ECMA-262规范定义
1、Object.prototype.toString( ) When the toString method is called, the following steps are taken:
Get the [[Class]] property of this object.
Compute a string value by concatenating the three strings “[object “, Result (1), and “]”.
Return Result (2)
2、new Array([ item0[, item1 [,…]]])
The [[Class]] property of the newly constructed object is set to “Array”.
因此检测对象是否是[object Array]就能判断是否是数组,call改变toString的this引用为待检测的对象,返回此对象的字符串表示,然后对比此字符串是否是'[object Array]',以判断其是否是Array的实例。
<script>
var arr = [ ];
alert (arr instanceof Array )//如果变量是给定引用类型,那么instanceof 操作符返回true,这里返回true
</script>
a是数组的话返回true,否则返回false
alert(Object.prototype.toString.call(array) == '[object Array]')