I need to know how to check the variable if its an Array or its an Object
var arr = ['foo', 'bar'];
var obj = {
0: 'foo',
1: 'bar'
}
document.write('arr is an: ' + typeof arr + ', obj is an: ' + typeof obj)
// The result is always:
// arr is an: object, obj is an: object
Is there any way to tell the difference between the two types?
Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.
isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .
This because in javascript all derived data type is always a type object. Included functions and array. In case you need to check if it's an array you can use isArray method of Array. and the result will be the same as the previous one.
Array.isArray(arr)
will return true
.
Array.isArray(obj)
will return false
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With