bethrobson / Head-First-JavaScript-Programming

417 stars 345 forks source link

typeof array ?? #13

Open adityathebe opened 9 years ago

adityathebe commented 9 years ago

var x = ["abc", 123]; var y = typeof x; console.log(y);

I was expecting the output "array" but it resulted as an object. How come array be an object ?

matthill82 commented 9 years ago

Array is a type of Object in JavaScript, the array is a mixed type array.

Sent from my iPhone So may be short.

On 24 Jul 2015, at 16:24, adityathebe notifications@github.com wrote:

var x = ["abc", 123]; var y = typeof x; console.log(y);

I was expecting the output "array" but it resulted as an object. How come array be an object ?

— Reply to this email directly or view it on GitHub.

AdiChat commented 9 years ago

JavaScript is an OOP language. An array of objects is an object. One can check if a variable is an array in several ways such as : var Arr = data instanceof Array; var Arr = Array.isArray(data); The most reliable way is : isArr = Object.prototype.toString.call(data) == '[object Array]'; In jQuery, we can use : var isArr = $.isArray(data);

Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.

The following code returns true : var a = new Array(1,2,3); a['key'] = 'experiment'; Array.isArray(a);

The following code returns false : var a = {1:1, 2:2, 3:3,'key':'experiment'}; Array.isArray(a)