![]() These all fail the test when an Array is from another window and Objects masquerading as Arrays. Here’s the ugly output table for these: Label See the MDN docs or check it out in the Observable notebook:įunction isArrayMdnOfficial ( objToCheck ) There’s a full set of implementation attempts and their tabulated output at take some of the approaches from “Determining with absolute accuracy whether or not a JavaScript object is an array” plus the official MDN polyfill for a spin. Therefore instanceof Array works, but only if you’re never going to share Arrays across windows/iframes, since at that point, they won’t have the same constructor/prototype. In JavaScript, the Array constructor/prototype is not shared across windows/iframes. See Determining with absolute accuracy whether or not a JavaScript object is an array by the semantics of instanceof, o instanceof Array works correctly only if o is an array created by that page’s original Array constructor (or, equivalently, by use of an array literal in that page). When checking for Array instance, Array.isArray is preferred over instanceof because it works through iframes. ![]() TypeĪrray with empty values using constructorĪlso known as the “why don’t we just use instanceof Array?” problem. Skip to where, we’re going to re-implement isArray. ![]() That’s it, off you go and solve problems.įor those who want some extra spicy JavaScript coding and want to understand what makes a JavaScript Array an Array you read on or No matter how it’s initialised and whether or not it’s been initialised using the local window’s Array or another one’s.įor people who are here to know how to detect if an object is an Array: use Array.isArray. Which is to say Array.isArray works, since it’s only true for Arrays, and it’s true for any Array. See below the full table for values for which Array.isArray evaluates to true for. Array.isArray behaviour with different typesĮxamples for this section at you can play around with the values list if anything is missing ( click here to do that).
0 Comments
Leave a Reply. |