ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

Is there any difference between the following statements in Javascript?

var multipleValues = [ ];

var multipleValues = new Array();

var multipleValues = Array();

user-image
تم إضافة السؤال من قبل Waqas Ahmed , Tech. PM / Software Designer , Aga Khan University Hospital
تاريخ النشر: 2016/10/22
Jonathan de Flaugergues
من قبل Jonathan de Flaugergues , software engineer , Abbeal

var multipleValues = [ ]; is an array literal syntax 

var multipleValues = new Array(); and var multipleValues = Array(); use invokation of Array constructor and both are equivalent because when Array is called as a function instead of constructor (using new keyword), it creates and initialises a new Array object. (the new keyword is injected).

The result of the three statements is the same. The difference come when an integer is passed as argument. var foo = [3] instantiate an array with a length of 1 with the '3' element and var bar = Array(3) instantiate an array with a length of 3 with 3 elements undefined.

Therefore, prefer the using of literals over constructors object because it's shorter, faster to execute and easier to read.

 

 

Mohd Nadeem Mohd Rehman Mohammed
من قبل Mohd Nadeem Mohd Rehman Mohammed , Software Engineer , Softworx Technologies

First Two are the same but first one is recommended to use for simplicity , readability and execution speed.

المزيد من الأسئلة المماثلة