Skip to content
Fix Code Error

How to check if an object is an array?

March 13, 2021 by Code Error
Posted By: Anonymous

I’m trying to write a function that either accepts a list of strings, or a single string. If it’s a string, then I want to convert it to an array with just the one item so I can loop over it without fear of an error.

So how do I check if the variable is an array?


I’ve rounded up the various solutions below and created a jsperf test. They’re all fast, so just use Array.isArray — it’s well-supported now and works across frames.

Solution

In modern browsers you can do:

Array.isArray(obj)

(Supported by Chrome 5, Firefox 4.0, IE 9, Opera 10.5 and Safari 5)

For backward compatibility you can add the following:

// 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]';
  }
};

If you use jQuery you can use jQuery.isArray(obj) or $.isArray(obj). If you use underscore you can use _.isArray(obj).

If you don’t need to detect arrays created in different frames you can also just use instanceof:

obj instanceof Array
Answered By: Anonymous

Related Articles

  • Combining items using XSLT Transform
  • error LNK2005: ✘✘✘ already defined in…
  • Fix top buttons on scroll of list below
  • Making Make Automatically Compile Objs from Headers…
  • How do I keep only the first map and when the game…
  • Perfomance issues with large number of elements in…
  • How does PHP 'foreach' actually work?
  • during wct test: Failed to load resource: the server…
  • Get the name of an object's type
  • Data binding between two Polymer elements using polymer 1.0
  • How to add 'load more' functionality to items on a…
  • Convert array to nested JSON object - Angular Material tree
  • Convert JavaScript string in dot notation into an…
  • How do I observe sub-property changes in Polymer?
  • TailwindCSS in Next.JS not rendering properly in Webkit
  • What are the undocumented features and limitations…
  • Wrong response from controller JSP
  • JavaScript - How to have collision with character…
  • AppCompat v7 r21 returning error in values.xml?
  • Display Grid does not work in Polymer correctly
  • Mismatch Detected for 'RuntimeLibrary'
  • How does the "this" keyword work?
  • Centering in CSS Grid
  • How to make vuetify navigation drawer to close group…
  • How do you check if a variable is an array in JavaScript?
  • TypeScript metadata reflection references other…
  • Javascript counting number of objects in object
  • Issue: C compiler used for C++ in CMake | CMake + git
  • For-each over an array in JavaScript
  • Memcached vs. Redis?
  • Adding Input Value Into An Object (Vue.js)
  • Is there any "font smoothing" in Google Chrome?
  • How do I correctly clone a JavaScript object?
  • data.table vs dplyr: can one do something well the…
  • HashSet vs. List performance
  • Switch between two frames in tkinter
  • For loop for HTMLCollection elements
  • What does do?
  • error LNK2038: mismatch detected for '_MSC_VER':…
  • How to show title in hover - css / jquery
  • how to integrate selenium driver for chrome and…
  • How can I access and process nested objects, arrays or JSON?
  • Programmatically Lighten or Darken a hex color (or…
  • Selenium using Java - The path to the driver…
  • How to convert number to words in java
  • Fastest way to iterate over all the chars in a String
  • Why does C++ code for testing the Collatz conjecture…
  • What methods of ‘clearfix’ can I use?
  • How can I pass a wct test while rearranging children…
  • What's the difference between eval, exec, and compile?
  • Manually adding a Userscript to Google Chrome
  • Change column type in pandas
  • How to generate a random string of a fixed length in Go?
  • Test for existence of nested JavaScript object key
  • How to detect Safari, Chrome, IE, Firefox and Opera browser?
  • How to specify line breaks in a multi-line flexbox layout?
  • Javascript - removing undefined fields from an object
  • Chrome / Safari not filling 100% height of flex parent
  • Fastest way to flatten / un-flatten nested JSON objects
  • What are access specifiers? Should I inherit with…
  • Angular.js Backbone.js and other MV* patterned js libraries?
  • How to save reference to "this" in Vue component?
  • Smart way to truncate long strings
  • Styling active-class in Vuetify
  • Run chrome in fullscreen mode on Windows
  • Valid values for android:fontFamily and what they map to?
  • JavaScript: How to pass object by value?
  • don't know what went wrong nav bar with Tailwind CSS…
  • Dart core element core-collapse
  • Why does git perform fast-forward merges by default?
  • What is Ember RunLoop and how does it work?
  • CSS3's border-radius property and…
  • Update nested object in array in ReactJs
  • using d3.js with aurelia framework
  • Item position in RecyclerView only changing when…
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Bootstrap Card - change width
  • VUE Error when run test unit
  • x264 / libx264 : Can only one I/P frame to be used…
  • How to serialize SqlAlchemy result to JSON?
  • How to Compile Object files into an Archive using Make
  • How to place object files in separate subdirectory
  • How to use Servlets and Ajax?
  • Vue v-bind:class not working immediately when…
  • How can I disable inherited css styles?
  • Vuetify v-list-item style change on hover
  • How to filter a RecyclerView with a SearchView
  • tkinter problem in displaying two frames using tkraise
  • Python selenium get contents of a webpage added by…
  • Calculate the mean by group
  • Replacing a 32-bit loop counter with 64-bit…
  • ReferenceError: obj is not defined using…
  • in doesn't call method on item change
  • Cannot read property 'nodeName' of null at…
  • Design DFA accepting binary strings divisible by a…
  • Ukkonen's suffix tree algorithm in plain English
  • Simplest way to create Unix-like continuous pipeline…
  • Object checking issue in JavaScript
  • How can I determine whether a 2D Point is within a Polygon?
  • Vue js dynamically added property not reactive

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Installing specific package versions with pip

Next Post:

How to make JavaScript execute after page load?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error