How do I check if an object is an array in JavaScript without using Array.isArray()?Alex K
To check if an object is an array in JavaScript without usingArray.isArray()
, you can use theObject.prototype.toString.call()
method. Here's an example:
1 2 3 4 5 6 7 8
function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]'; } // Example usage console.log(isArray([1, 2, 3])); // Output: true console.log(isArray({ key: 'value' })); // Output: false
In the above code, theisArray()
function takes an object as an argument. It usesObject.prototype.toString.call(obj)
to retrieve the internal[[Class]]
property of the object, which is a string representation of its type. For an array, the[[Class]]
property will be"[object Array]"
.
By comparing the result ofObject.prototype.toString.call(obj)
with"[object Array]"
, we can determine if the object is an array or not. If the comparison returnstrue
, then the object is an array. Otherwise, it is not.
Note that this method works for most cases, but it may not be reliable if you're dealing with arrays that originate from different frames or contexts (e.g., iframes) due to differences in their[[Class]]
values. In such cases, usingArray.isArray()
is recommended for accurate results.
Similar Questions
How do I check if a variable is an array in JavaScript without using Array.isArray()?
How do I check if an object is an array in JavaScript?
How do I check if an object is an array in JavaScript?
How do I check if a value is an empty object in JavaScript without using Object.keys()?
How do I check if an array is equal to another array in JavaScript?
How do I check if a key exists in an object in JavaScript?
How do I check if an object is empty in JavaScript?
How do I check if an object is empty in JavaScript?
How do I check if a variable is an object in JavaScript?
How do I check if a value is an object in JavaScript?
How do I check if a value exists in an array of objects in JavaScript?
How do I check if a variable is an integer in JavaScript without using Number.isInteger()?
How do I check if a value is an integer in JavaScript without using Math.floor()?
How do I check if a value is an empty array or object in JavaScript?
How do I check if an element exists in an array in JavaScript?
How do I check if an array is empty in JavaScript?
How do I check if an array is empty in JavaScript?
How can I convert an object to an array in JavaScript without losing keys?
How do I check if a value is an empty string in JavaScript without using length?