区分阵列和“散列”。在Javascript中 [英] Differentiating between arrays and "hashes" in Javascript

查看:85
本文介绍了区分阵列和“散列”。在Javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了使我的一个函数的语法更好,我需要能够判断一个特定的参数是一个数组还是哈希(我知道它只是对象)。

In order to make the syntax for one of my functions nicer, I need to be able to tell whether a specific parameter is an array or "hash" (which I know are just objects).

Typeof不起作用,因为它们都返回相同的东西

Typeof doesn't work, because they both return the same thing

typeof {foo:bar} //对象

typeof [foo,bar] //对象

那么我如何区分两者?

我知道有效,但我希望有一个更好的方式

I know this works, but I'm hoping there's a nicer way

({foo:bar})。constructor // Object()

([foo,bar])。构造函数// [undefined]

编辑
啊,看来firebug中的[undefined]和Array是一样的。有点奇怪。

EDIT Ah, it seems [ undefined ] in firebug is the same thing as Array. Kind of weird.

推荐答案

你可以像SLaks建议的那样检查长度属性,但是一旦你传递了一个函数对象你会感到惊讶,因为它实际上有一个长度属性。此外,如果对象定义了一个长度属性,你将再次得到错误的结果。

You could check the length property as SLaks suggested, but as soon as you pass it a function object you'll be surprised, because it in fact has a length property. Also if the object has a length property defined, you'll get wrong result again.

你最好的选择可能是:

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

jQuery使用它,还有一对其他人......: )

jQuery uses it, and a "couple of" other people... :)

它比实例方式更加失败。以下文章还建议使用该方法:

It is more fail proof than the instanceof way. The method is also suggested by the following article:

'instanceof'被视为有害(或如何编写健壮的'isArray') (@ kagax)

'instanceof' considered harmful (or how to write a robust 'isArray') (@kagax)

另外要补充一点,这个函数几乎与ES 5中的 Array.isArray 函数相同规范:

Another thing to add that this function is almost identical to the Array.isArray function in ES 5 spec:


15.4.3.2 Array.isArray(arg)


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

  2. 如果 arg 的[[Class]]
    内部属性的值为Array
    然后返回 true

  3. 返回 false

  1. If Type(arg) is not Object, return false.
  2. If the value of the [[Class]] internal property of arg is "Array", then return true.
  3. Return false.


这篇关于区分阵列和“散列”。在Javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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