Javascript do not have true array. because when i tested out this thing in google console i was surprised to see that there is no difference between an object and an array.
var obj = {};
var arr = [];
typeof obj; //object
typeof arr; //object
i am curious to know
why this is so?
and
Do really javascript possess false array?
and
Is this
typeof
is wrong , i mean do this not differentiate between object and an array?
and
what are the conditions to be a true array?
thanks!
JavaScript is a dynamic language and its objects are very flexible. And there is really no gurantee that, an object you have is of particular type. Because we can do duck typing .
If you want to know if an object is an Array or not, you can use this
Object.prototype.toString.call(obj) == '[object Array]';
This is taken from the underscore.js library's _.isArray
function. Since it is popular and widely used, this method should be reliable.
If your environment supports ECMA 5.1, then you can also use Array.isArray
function, like this
Array.isArray(obj);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.