Jak sprawdzić, czy obiekt jest tablicą?

Próbuję napisać funkcję, która albo akceptuje listę łańcuchów, albo pojedynczy łańcuch. Jeśli jest to ciąg znaków, to chcę przekonwertować go do tablicy z tylko jednym elementem, więc mogę zapętlić go bez obawy o błąd.

Więc jak sprawdzić, czy zmienna jest tablicą?


Zebrałem różne rozwiązania poniżej i stworzyłem test jsperf . Wszystkie są szybkie, więc po prostu użyj Array.isArray -- to dobrze obsługiwane teraz i Działa na całym ramki .

Author: mpen, 2011-01-23

30 answers

W nowoczesnych przeglądarkach można zrobić:

Array.isArray(obj)

(Obsługiwane przez Chrome 5, Firefox 4.0, IE 9, Opera 10.5 i Safari 5)

Dla kompatybilności wstecznej można dodać:

// only implement if no native implementation is available
if (typeof Array.isArray === 'undefined') {
  Array.isArray = function(obj) {
    return Object.prototype.toString.call(obj) === '[object Array]';
  }
};

Jeśli używasz jQuery możesz użyć jQuery.isArray(obj) lub $.isArray(obj). Jeśli używasz podkreślenia, możesz użyć _.isArray(obj).

Jeśli nie musisz wykrywać tablic utworzonych w różnych klatkach, możesz również użyć instanceof:

obj instanceof Array
 1233
Author: Fela Winkelmolen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-20 10:14:08

Metoda podana w standardzie ECMAScript do znalezienia klasy obiektu polega na użyciu metody toString z Object.prototype.

if( Object.prototype.toString.call( someVar ) === '[object Array]' ) {
    alert( 'Array!' );
}

Lub możesz użyć typeof, aby sprawdzić, czy jest to ciąg znaków:

if( typeof someVar === 'string' ) {
    someVar = [ someVar ];
}

Lub jeśli nie martwisz się o wydajność, możesz po prostu zrobić concat do nowej pustej tablicy.

someVar = [].concat( someVar );

Jest też konstruktor, który możesz bezpośrednio odpytywać:

if (somevar.constructor.name == "Array") {
    // do something
}

Sprawdź dokładne leczenie z@T. J. Crowder ' s blog, jako posted in his comment below.

Sprawdź ten benchmark aby dowiedzieć się, Która metoda działa lepiej: http://jsben.ch/#/QgYAV

From @ Bharath Konwertuj łańcuch znaków na tablicę używając Es6 dla zadanego pytania:

const convertStringToArray = (object) => {
   return (typeof object === 'string') ? Array(object) : object 
}

Przypuśćmy:

let m = 'bla'
let n = ['bla','Meow']
let y = convertStringToArray(m)
let z = convertStringToArray(n)
console.log('check y: '+JSON.stringify(y)) . // check y: ['bla']
console.log('check y: '+JSON.stringify(z)) . // check y: ['bla','Meow']
 1962
Author: user113716,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 23:30:09

Najpierw sprawdziłbym czy Twoja implementacja obsługuje isArray:

if (Array.isArray)
    return Array.isArray(v);
Możesz również spróbować użyć operatora instanceof
v instanceof Array
 1294
Author: ChaosPandion,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-23 18:55:46

JQuery oferuje również $.isArray() "metoda": {]}

var a = ["A", "AA", "AAA"];

if($.isArray(a)) {
  alert("a is an array!");
} else {
  alert("a is not an array!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 302
Author: janr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-17 07:41:25

Jest to najszybsza spośród wszystkich metod (wszystkie przeglądarki obsługiwane):

function isArray(obj){
    return !!obj && obj.constructor === Array;
}
 107
Author: shinobi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-19 08:37:44

Imagine you have this array below :

var arr = [1,2,3,4,5];

Javascript (nowe i starsze przeglądarki):

function isArray(arr) {
  return arr.constructor.toString().indexOf("Array") > -1;
}

Lub

function isArray(arr) {
  return arr instanceof Array;
}

Lub

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

Więc nazwij to tak:

isArray(arr);

Javascript (IE9+, Ch5+, FF4+, Saf5+, Opera10.5+)

Array.isArray(arr);

JQuery:

$.isArray(arr);

Kątowy:

angular.isArray(arr);

Podkreślenie i Lodash:

_.isArray(arr);
 49
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-21 07:10:31

Array.isArray działa szybko, ale nie jest obsługiwany przez wszystkie wersje przeglądarek. Możesz więc zrobić wyjątek dla innych i użyć metody uniwersalnej:

    Utils = {};    
    Utils.isArray = ('isArray' in Array) ? 
        Array.isArray : 
        function (value) {
            return Object.prototype.toString.call(value) === '[object Array]';
        }
 34
Author: CruorVult,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-18 11:18:11

Prosta funkcja do sprawdzenia:

function isArray(object)
{
    return object.constructor === Array;
}
 32
Author: MidnightTortoise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-27 19:40:03

Jest tylko jedno rozwiązanie liniowe na to pytanie

x instanceof Array

Gdzie X jest zmienną zwróci true, Jeśli X jest tablicą, a false, jeśli nie jest.

 18
Author: Vikash Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-08 12:48:15

Jak mówi MDN TUTAJ :

Użyj Tablicy.isArray lub obiekt.prototyp.toString.call to different regularne obiekty z tablic

Tak:

  • Object.prototype.toString.call(arr) === '[object Array]', lub

  • Array.isArray(arr)

 17
Author: ajax333221,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-14 21:02:15

Możesz sprawdzić typ zmiennej, czy jest to tablica z;

var myArray=[];

if(myArray instanceof Array)
{
....
}
 15
Author: Ahmet DAL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-15 08:58:07

Stworzyłbym funkcję do testowania typu obiektu, z którym masz do czynienia...

function whatAmI(me){ return Object.prototype.toString.call(me).split(/\W/)[2]; }

// tests
console.log(
  whatAmI(["aiming","@"]),
  whatAmI({living:4,breathing:4}),
  whatAmI(function(ing){ return ing+" to the global window" }),
  whatAmI("going to do with you?")
);

// output: Array Object Function String

Wtedy możesz napisać proste polecenie if...

if(whatAmI(myVar) === "Array"){
    // do array stuff
} else { // could also check `if(whatAmI(myVar) === "String")` here to be sure
    // do string stuff
}
 15
Author: Billy Moon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-17 07:46:17

Robię to w bardzo prosty sposób. Mi pasuje. Jakieś wady?

Array.prototype.isArray = true;

a=[]; b={};
a.isArray  // true
b.isArray  // (undefined -> false)
 13
Author: rsbkk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-04 06:58:20

To moja próba poprawienia tej odpowiedzi biorąc pod uwagę komentarze:

var isArray = myArray && myArray.constructor === Array;

Usuwa if / else i uwzględnia możliwość, że tablica jest NULL lub undefined

 12
Author: Dexygen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:51

Https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/isArray

Array.isArray = Array.isArray || function (vArg) {
    return Object.prototype.toString.call(vArg) === "[object Array]";
};
 11
Author: Safareli,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-01 05:32:31

Zaktualizowałem jsperf fiddle z dwóch alternatywnych metod, jak również sprawdzanie błędów.

Okazuje się, że metoda definiująca stałą wartość w prototypach 'Object' i 'Array' jest szybsza niż jakakolwiek inna metoda. Jest to dość zaskakujący wynik.

/* Initialisation */
Object.prototype.isArray = function() {
  return false;
};
Array.prototype.isArray = function() {
  return true;
};
Object.prototype._isArray = false;
Array.prototype._isArray = true;

var arr = ["1", "2"];
var noarr = "1";

/* Method 1 (function) */
if (arr.isArray()) document.write("arr is an array according to function<br/>");
if (!noarr.isArray()) document.write("noarr is not an array according to function<br/>");
/* Method 2 (value) - **** FASTEST ***** */
if (arr._isArray) document.write("arr is an array according to member value<br/>");
if (!noarr._isArray) document.write("noarr is not an array according to member value<br/>");

Te dwie metody nie działają, jeśli zmienna przyjmuje wartość niezdefiniowaną, ale działają, jeśli masz pewność, że mają wartość. W odniesieniu do sprawdzania z wydajność jeśli wartość jest tablicą lub pojedynczą wartością, druga metoda wygląda jak prawidłowa szybka metoda. Jest nieco szybszy niż "instanceof" w Chrome, dwa razy szybciej niż druga najlepsza metoda w Internet Explorer, Opera i Safari (na moim komputerze).

 11
Author: le_top,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-01 11:10:28

Wiem, że ludzie szukają jakiegoś surowego podejścia do javascript. Ale jeśli chcesz mniej myśleć, zajrzyj tutaj: http://underscorejs.org/#isArray

_.isArray(object) 

Zwraca true, jeśli obiekt jest tablicą.

(function(){ return _.isArray(arguments); })();
=> false
_.isArray([1,2,3]);
=> true
 10
Author: Eugene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-28 13:27:56

Jeśli tylko dwa rodzaje wartości, które mogą być przekazane do tej funkcji, to łańcuch znaków lub tablica łańcuchów, zachowaj to w prosty sposób i użyj typeof Sprawdź możliwość ciągu znaków:

function someFunc(arg) {
    var arr = (typeof arg == "string") ? [arg] : arg;
}
 5
Author: Tim Down,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-01-23 19:51:12

Najlepszym rozwiązaniem, jakie widziałem, jest wymiana między przeglądarkami dla typeof. Sprawdź rozwiązanie Angusa Crolla Tutaj .

Wersja TL;DR jest poniżej, ale artykuł jest świetną dyskusją na ten temat, więc powinieneś go przeczytać, jeśli masz czas.

Object.toType = function(obj) {
    return ({}).toString.call(obj).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
}
// ... and usage:
Object.toType([1,2,3]); //"array" (all browsers)

// or to test...
var shouldBeAnArray = [1,2,3];
if(Object.toType(shouldBeAnArray) === 'array'){/* do stuff */};
 5
Author: John Wundes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-03-23 17:16:43

Oto moje leniwe podejście:

if (Array.prototype.array_ === undefined) {
  Array.prototype.array_ = true;
}

// ...

var test = [],
    wat = {};

console.log(test.array_ === true); // true
console.log(wat.array_ === true);  // false

Wiem, że to świętokradztwo "zadzierać" z prototypem, ale wydaje się działać znacznie lepiej niż zalecana metoda toString .

Uwaga: pułapką tego podejścia jest to, że nie będzie działać poza iframe granicami , ale dla mojego przypadku użycia nie jest to problem.

 5
Author: namuol,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-06 02:07:47

Istnieje ładny przykład w książce Stoyana Stefanova Wzorce JavaScript , które zakładają obsługę wszystkich możliwych problemów, a także wykorzystanie metody ECMAScript 5 Array.isArray () .

Oto jest:

if (typeof Array.isArray === "undefined") {
    Array.isArray = function (arg) {
        return Object.prototype.toString.call(arg) === "[object Array]";
    };
}

Przy okazji, jeśli używasz jQuery, możesz użyć jej metody $.isArray()

 5
Author: Salvador Dali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 22:27:21

Ta funkcja zamieni prawie wszystko w tablicę:

function arr(x) {
    if(x === null || x === undefined) {
        return [];
    }
    if(Array.isArray(x)) {
        return x;
    }
    if(isString(x) || isNumber(x)) {
        return [x];
    }
    if(x[Symbol.iterator] !== undefined || x.length !== undefined) {
        return Array.from(x);
    }
    return [x];
}

function isString(x) {
    return Object.prototype.toString.call(x) === "[object String]"
}

function isNumber(x) {
    return Object.prototype.toString.call(x) === "[object Number]"
}

Używa kilku nowszych funkcji przeglądarki, więc możesz chcieć to polyfill dla maksymalnej obsługi.

Przykłady:

> arr(null);
[]
> arr(undefined)
[]
> arr(3.14)
[ 3.14 ]
> arr(1/0)
[ Infinity ]
> gen = function*() { yield 1; yield 2; yield 3; }
[Function: gen]
> arr(gen())
[ 1, 2, 3 ]
> arr([4,5,6])
[ 4, 5, 6 ]
> arr("foo")
[ 'foo' ]

N. B. ciągi znaków zostaną przekształcone w tablicę z pojedynczym elementem zamiast tablicy znaków. Usuń isString sprawdź, czy wolisz odwrotnie.

Użyłem Array.isArray tutaj, ponieważ jest to najbardziej wytrzymały , a także najprostszy.

 5
Author: mpen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-24 16:01:37

Najprostszy i najszybszy sposób sprawdzenia, czy obiekt jest tablicą, czy nie.

 var arr = [];
  arr.constructor.name ==='Array'  //return true;

Lub

arr.constructor ===Array //return true;

Lub możesz zrobić funkcję użytkową:

function isArray(obj){ return obj && obj.constructor ===Array}

Użycie:

isArray(arr); //return true
 5
Author: Sheelpriy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-29 06:25:02

Poniższy tekst może być użyty, jeśli wiesz, że Twój obiekt nie ma metody concat.

var arr = [];
if (typeof arr.concat === 'function') {
    console.log("It's an array");
}
 5
Author: yesil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-26 07:00:00

Można jest metodą isArray, ale wolałbym sprawdzić z

Object.getPrototypeOf(yourvariable) === Array.prototype

 5
Author: STEEL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-28 17:21:06

Najlepszą praktyką jest porównanie go za pomocą constructor, czegoś takiego

if(some_variable.constructor === Array){
  // do something
}

Możesz też użyć innych metod, takich jak typeOf, konwertując je na ciąg znaków, a następnie porównując, ale porównywanie go z typem danych jest zawsze lepszym podejściem.

 5
Author: Atishay Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-10 08:08:45
A = [1,2,3]
console.log(A.map==[].map)

W poszukiwaniu najkrótszej wersji tutaj jest to, co mam do tej pory.

Uwaga, nie ma idealnej funkcji, która zawsze wykryje wszystkie możliwe kombinacje. Lepiej znać wszystkie możliwości i ograniczenia swoich narzędzi, niż oczekiwać magicznego narzędzia.

 4
Author: exebook,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-03-12 02:57:43
function isArray(value) {
    if (value) {
        if (typeof value === 'object') {
            return (Object.prototype.toString.call(value) == '[object Array]')
        }
    }
    return false;
}

var ar = ["ff","tt"]
alert(isArray(ar))
 4
Author: RoboTamer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-30 09:56:27

Prosta funkcja do sprawdzania, czy wartość wejściowa jest tablicą jest następująca:

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

To działa między przeglądarkami i ze starszymi przeglądarkami. To jest wyciągnięte z postu T. J. Crowders na blogu

 4
Author: Brad Parks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-02 00:29:54

Możesz spróbować tego:

var arr = []; (or) arr = new Array();
var obj = {}; (or) arr = new Object();

arr.constructor.prototype.hasOwnProperty('push') //true

obj.constructor.prototype.hasOwnProperty('push') // false
 4
Author: VIJAY P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-25 15:54:37