Creating arrays of objects in javascript

I am learning javascript coming from a .NET background. I have a question about how to handle arrays of objects, create and manipulate is not as simple / obvious as .NET.

Often in .NET code, I use structs (C #) or structures (VB.NET) to control simple value constructions, for example (in VB.NET):

Public Structure WidgetsStruc Public Name As String Public LocX As Integer Public LocY As Integer End Structure Private myWidgets As New WidgetsStruc myWidgets.LocX = 35 myWidgets.LocY = 312 myWidgets.Name = "compass" Messagebox(myWidgets.Name) ' shows 'compass' ... 

there is nothing equivalent in javascript from my research, although you can use an object and "click" it on an array, as shown below:

  var widget = new Object(); var widgetTemplates = new Array(); widgetTemplates.push(widget); widgetTemplates[0].name = "compass"; widgetTemplates[0].LocX = 35; widgetTemplates[0].LocY = 312; alert(widgetTemplates[0].name); // also shows 'compass' 

Perhaps I’m not used to working in a more weakly typed language, but the above JavaScript does not seem optimal (for example, you need to "push" an object without an declared structure into an array and initialize the variables afterwards, plus "pop" and "slice" for deletion).

Do I have this right? Is there a better or easier way to declare and use arrays of objects? I also learned JSON, but not quite sure how to use this to manipulate user-defined objects in an array.

Like JavaScript n00b - thanks for any guidance!

+6
source share
1 answer

You can use the conventions of objects and arrays:

 var widgetTemplats = [ { name: 'compass', LocX: 35, LocY: 312 }, { name: 'another', LocX: 52, LocY: 32 } ] 

For simple things like this, the lack of a coercive structure is pretty normal. If you need a more rigorous structure or bind behavior to your objects, you should look at classes in JavaScript:

 var Widget = function(name, x, y) { this.name = name; this.LocX = x; this.LocY = y; }; var widgets = [ new Widget('compass', 35, 312), new Widget('another', 52, 32) ]; 
+10
source

Source: https://habr.com/ru/post/944755/


All Articles