Either we check type of array or object it always print object in JavaScript. Why so?
let arr=[1,3,4];
let obj={1:"44",num:44};
console.log(typeof(arr)) //object
console.log(typeof(obj)) //object
Is there any way to see typeof(array) as array?
Either we check type of array or object it always print object in JavaScript. Why so?
let arr=[1,3,4];
let obj={1:"44",num:44};
console.log(typeof(arr)) //object
console.log(typeof(obj)) //object
Is there any way to see typeof(array) as array?
Try using the instanceof operator
const arr = [];
console.log(arr instanceof Array); // true
const obj = {};
console.log(obj instanceof Array); // false
Because an array
is technically a type of object
- just with certain abilities and behaviors, for instance additional methods like Array.prototype.push()
and Array.prototype.unshift()
. Arrays are regular objects where there is a particular relationship between integer-key-ed properties and the length property.
To determine whether you have an array specifically, you can use Array.isArray()
.
In JavaScript, almost everything is an Object.
It uses prototype chain to achieve inheritance.
you can just console.log( [] ) and see the prototype part to see that it inherit from objects.
Here is a simple way to make an your own Array.
function MyArray(){
Object.defineProperty(this, 'length', {
value: 0,
enumerable: false,
writable: true,
})
}
MyArray.prototype.push = function(elem){
this[this.length] = elem
this.length++
return this.length
}
MyArray.prototype.isMyArray = function(instance){
return instance instanceof MyArray
}
var arr = new MyArray()
arr.push(1)
arr.push(2)
arr.push(3)
console.log('instance', MyArray.prototype.isMyArray( arr ))
// instance true
console.log('object', typeof arr)
// object object