这是一种可接受的方法来确定对象是否是JavaScript中的数组? [英] Is this an acceptable way to determine if an object is an array in JavaScript?

查看:73
本文介绍了这是一种可接受的方法来确定对象是否是JavaScript中的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常使用此代码来确定数组是否真的是一个数组...

I have often used this code to determine if an array is really an array...

Object.prototype.toString.call(array) == '[object Array]'

我最近开始更改我的回调测试 typeof callback =='function' to callback instanceof Function ,因为我读过Safari和Chrome会告诉你一个正则表达式literal是一个使用前者的函数(当我测试它时它会这样做。)

I recently started changing my callback tests from typeof callback == 'function' to callback instanceof Function, because I read that Safari and Chrome will tell you a regex literal is a function using the former (and it did when I tested it).

现在,我决定检查这段代码,看看我是否可以替换上面的详细代码...

Now, I decided to check this code to see if I can replace the verbose code above...

array instanceof Array

有效。

两者在jsFiddle上的比较

那么,后一种方法有什么问题吗?我假设可能是因为第一个代码示例在Google中出现得更频繁。

So, is there any issues with the latter method? I assumed there may be because the first code example came up much more often in Google.

推荐答案

使用<$的两个问题对于数组,c $ c> instanceof 是:


  • 返回 false 当数组来自另一个窗口或框架时

  • 如果数组构造函数被覆盖则中断

  • Returns false when the array is from another window or frame
  • Breaks if the Array constructor has been overwritten

以下是kangax的一篇文章,我第一次看到你的第一个技术(也用于jQuery): http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write -a-robust-isarray /

The following is an article by kangax where I first saw your first technique (also used in jQuery): http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/

这篇关于这是一种可接受的方法来确定对象是否是JavaScript中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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