Several methods and differences for JavaScript to create empty objects and empty arrays

Source: Internet
Author: User

Here are three ways to create an empty object:

var emptyObj1 = {}; var New Object (); var emptyObj2 = object.create (Object.prototype);

They are the same for JavaScript, and the newly created three objects inherit all the properties and methods of object, so emptyobj1.tostring equals Object.prototype.toString. But be aware that {}.tostring is an error!

Similarly, there are empty array problems:

var emptyArr1 = []; var New Array ();

The above two lines are no different

var arr1 = [' foo ', ' Bar ']; var New Array (' foo ', ' Bar ');

There's no difference between these two lines.

var arr1 = [3];  Arr1.length = = 1, arr1[0] = = 3varnew Array (3); Arr2.length = = 3, arr2[0] = = undefined

The above two lines are different

var arr1 = [];arr1[0] = ' first element '; Console.log (arr1);//["first element"]var C4>new  Array (); arr2[0] = ' first element '; Console.log (ARR2);//["first element"]var ARR3 = object.create (array.prototype); arr3[0] = ' first element 'Console.log (ARR3);//Array {0: "First Element "}

The above code shows that the array created with Object.create returns an object, and if arr3[0] = ' first element ' is replaced with Arr3.push (' first element '), the output will be the same as the above two.

Reference Links:

Http://stackoverflow.com/questions/251402/create-an-empty-object-in-javascript-with-or-new-object

Http://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar

Several methods and differences for JavaScript to create empty objects and empty arrays

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.