使用typeof()区分javascript中的数组和哈希 [英] Distinguish between array and hash in javascript with typeof()

查看:65
本文介绍了使用typeof()区分javascript中的数组和哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

在javascript中我们如何识别对象是Hash还是数组?

在javascript中

In javascript

typeof([])

typeof({})

都返回对象 。

如何在Javascript中可靠地区分数组和关联数组?

How can I reliably distinguish between an array and an associative array in Javascript?

我想过测试有问题的对象以查看它是否具有length属性(表明它将是一个数组),但是下面的内容也将被视为一个数组:

I have thought of testing the object in question to see if it has the "length" attribute (indicating it would be an array), but what then the following would also be seen as an array:

{length:5}


推荐答案

现代浏览器内置 Array.isArray

对于旧版浏览器,您可以测试该功能并在必要时添加。

For older browsers, you can test for that function and add it when necessary.

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

alert( Array.isArray( [] ) );






编辑:

数组。 isArray 是ECMAScript 5的一部分

Array.isArray is part of ECMAScript 5:


15.4.3.2 Array.isArray( arg)

isArray函数接受一个参数arg,如果参数是类内部属性为Array的对象,则返回布尔值true;否则返回false。采取以下步骤:

The isArray function takes one argument arg, and returns the Boolean value true if the argument is an object whose class internal property is "Array"; otherwise it returns false. The following steps are taken:


  1. 如果Type(arg)不是Object,则返回false。

  2. 如果arg的[[Class]]内部属性的值为Array,则返回true。

  3. 返回false。


这篇关于使用typeof()区分javascript中的数组和哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆