Javascript 如何检查对象是否不是数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2265922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:31:58  来源:igfitidea点击:

How to check if an object is not an array?

javascripttypestypeof

提问by hojberg

So i have a function that needs to check if an argument is an object, but this fails because:

所以我有一个函数需要检查一个参数是否是一个对象,但这失败了,因为:

typeof [] // returns 'object'

This is a classic javascript gotcha, but i cant remember what to do to actually accept objects, but not arrays.

这是一个经典的 javascript 问题,但我不记得该怎么做才能真正接受对象,而不是数组。

回答by Tomas Vana

Try something like this :

尝试这样的事情:

obj.constructor.toString().indexOf("Array") != -1

or (even better)

或(甚至更好)

obj instanceof Array

回答by Pointy

All these answers suggesting that you check to see (one way or another) if an object is an instance of the "Array" class (that is, constructed by "Array") are really not safe solutions. They'll work sometimes, maybe most of the time, but all the major frameworks have moved away from that approach. One of the main problems with it comes about when there's interaction between multiple windows (generally, a parent window and one or more frame or iframe windows). If you pass an array object created in one window into an API resident in another window, all these tests will fail. Why? Because what you're testing is whether an object is an instance of the "Array" class in your local window context. In other words, when you reference "Array" in

所有这些建议您检查(以一种或另一种方式)对象是否是“Array”类(即由“Array”构造)的实例的答案都不是安全的解决方案。它们有时会起作用,也许大部分时间会起作用,但所有主要框架都已远离这种方法。当多个窗口(通常是一个父窗口和一个或多个框架或 iframe 窗口)之间存在交互时,它的主要问题之一就会出现。如果您将在一个窗口中创建的数组对象传递到驻留在另一个窗口中的 API,则所有这些测试都将失败。为什么?因为您要测试的是对象是否是本地窗口上下文中“Array”类的实例。换句话说,当您在

if (myobject instanceof Array) { ... }

what you're referencing is window.Array, of course. Well, an array constructed in another windowis notgoing to be an instance of the Array class in your window!

你所指的是window.Array,当然。那么,在构建一个数组另一个窗口不是将成为Array类的一个实例,在你的窗口!

Checking the constructor name is probably a little safer, though it's still risky. In my opinion, you're better off taking a duck-typing approach. That is, instead of asking, "Is this an Array?" ask instead, "does this object seem to support some particular set of Array APIs I need in this circumstance?" For example, "does this object have a lengthproperty?" Javascript is a pretty "soft" language, and just about everything's mutable. Thus even if you do find out something was constructed by "Array", you stillreally don't know for sure what you can do with it or to it.

检查构造函数名称可能更安全一些,尽管它仍然存在风险。在我看来,你最好采用鸭子打字的方法。也就是说,不是问“这是一个数组吗?” 而是问,“这个对象似乎支持我在这种情况下需要的某些特定的数组 API 集?” 例如,“这个对象有length属性吗?” Javascript 是一种非常“软”的语言,几乎所有东西都是可变的。因此,即使您确实发现某些东西是由“Array”构造的,您仍然不确定您可以用它或对它做什么。

[edit] Thanks for that link, @Lachlan - here's a very clear description of the issues: http://juhukinners.com/2009/01/11/typeof-considered-useless-or-how-to-write-robust-type-checks/

[编辑] 感谢这个链接,@Lachlan - 这是对问题的非常清楚的描述:http://juhukinners.com/2009/01/11/typeof-thinked-useless-or-how-to-write-robust-类型检查/

回答by Arley

To determine whether a given object is an array, ECMAScript 5 introduces the Array.isArray()method, which is currently supported across all modern browsers. Refer to this ECMAScript compatibility table.

为了确定一个给定的对象是否是一个数组,ECMAScript 5 引入了Array.isArray()方法,目前所有现代浏览器都支持该方法。请参阅此ECMAScript 兼容性表

To determine the class of a particular object, you can use the Object.prototype.toString()method.

要确定特定对象的类,您可以使用Object.prototype.toString()方法。

Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"

回答by IliasT

To test if something is an instance of an Array:

要测试某物是否是Array的实例:

const arr = [1,2,3];
Array.isArray(arr);  // true

To test is something is an instance of an Object:

要测试的东西是Object 的一个实例:

const obj = { 1: 'a', 2: 'b', 3: 'c' };
obj.constructor === Object;  // true

Notethe latter would throw an error if objis nullor undefined, in that case you could use: typeof obj === 'object'or just do a null check: obj && obj.constructor === Object.

请注意,如果objnullundefined,后者会抛出错误,在这种情况下,您可以使用:typeof obj === 'object'或只进行空检查: obj && obj.constructor === Object

回答by Hyyan Abo Fakher

Arrays are objects in javascript after all ,so all you need to do is to check if the type of variable is an object and in the same time this object is not instance of Array class.

数组毕竟是javascript中的对象,所以你需要做的就是检查变量的类型是否是一个对象,同时这个对象不是Array类的实例。

var obj = {fname:'John',lname:'Doe'};

if(typeof obj === 'object' && !(obj instanceof Array)){
  return true ;
} else  {
  return false;
}

回答by Andrew Hedges

For what it's worth, here is how jQuery checks whether something is an array:

对于它的价值,这里是 jQuery 如何检查某个东西是否是一个数组:

isArray: function( arr ) {
    return !!arr && arr.constructor == Array;
}

But, this articlerecommends doing it like this:

但是,本文建议这样做:

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

回答by Arnold Zokas

Have you tried this:

你有没有试过这个:

var test = [];
if(test instanceof Array) {
 ...
}

EDIT: This method doesn't work in multi-frame DOM environments (‘typeof' considered useless - or how to write robust type checks). (via Pointy)

编辑:此方法在多帧 DOM 环境中不起作用(“typeof”被认为是无用的 - 或者如何编写健壮的类型检查)。(通过Pointy

回答by JoeLoco

Look this package

看这个包

Verify if a given object is not an array for old browsers

验证给定对象是否不是旧浏览器的数组

https://www.npmjs.com/package/notisarray

https://www.npmjs.com/package/notisarray

回答by Anish Nair

var obj = {first: 'Stack', last: 'Overflow'};
// var obj = ['Stack', 'overflow']; //You can uncomment this line and comment the above to check..

if(Object.prototype.toString.call(obj) !== '[object Array]') {
    //your code..
    var str = '';
    for(var k in obj) {
     str = str + obj[k] + ' ';
    }
    console.log('I love ', str);
    alert('I love ' + str);
} else {
 console.log('Could not process. Probably an array');
  alert('Could not process. Probably an array');
}

console.log('Length is: ', Object.keys(obj).length);
alert('Length is: ' + Object.keys(obj).length);

Let inputbe an Arrayor an Object

input是一个Array或一个Object

To check if an object is an Array
if(Object.prototype.toString.call(input) === '[object Array]') {}

检查对象是否为 Array
if(Object.prototype.toString.call(input) === '[object Array]') {}

To check if an object is an Object
if(Object.prototype.toString.call(input) === '[object Object]') {}

检查对象是否为 Object
if(Object.prototype.toString.call(input) === '[object Object]') {}


Please note Object.keys(input).lengthwill return you the length for both Array and Object.


请注意Object.keys(input).length将返回数组和对象的长度。

JS Fiddle examplefor the same

相同的JS Fiddle 示例

回答by Joey Dias

please use Object.prototype.toString.call({}).slice(8,-1)==="Object"this works for all datatype you can replace the parameter inside call function and the comparison also to check for different datatypes. it works for null check as well

Object.prototype.toString.call({}).slice(8,-1)==="Object"将此适用于所有数据类型,您可以替换调用函数中的参数,并进行比较以检查不同的数据类型。它也适用于空检查