What is the difference between each of the following array definitions.
var myArray = [];
v开发者_JS百科ar myArray = {};
var myArray = new Array();
The first and third are equivalent and create a new array. The second creates a new empty object, not an array.
var myArray = []; //create a new array
var myArray = {}; //creates **a new empty object**
var myArray = new Array(); //create a new array
var myObject = {};
is equivalent to var myObject = new Object();
So, the second example is not an Array
but a general Object
.
This can get confusing as Array
is a class and Object
is a class - more precisely Array
is a sub-class of Object
. So, by and large, Object
semantics are applicable to an Array
:
var o = [];
o.push('element1');
o.push('element2');
o['property1'] = 'property value'; // define a custom property.
console.log(o.property1);
console.log(o.length); // Outputs '2' as we've only push()'ed two elements onto the Array
精彩评论