I would appreciate some help. I am trying to do a small javascript program that does the following:
1) I already have a few arrays with some information about different cars. For example:
var brand = ["Audi", "Ford", "Peugeot", "Nissan"];
var color = ["red", "black", "black", "white"];
2) Then, I would like to create a class that creates a new car and receives the properties through a method that retrieves them from the ones I have stored in the array,
Is something like this correct?
function newcar() {
this.prototype.loadinfo = function() {
var cbrand = brand[0];
var ccolor = color[0];
}
}
Sorry if this is horribly wrong, but the reason I am asking is that I didn’t find any information about this particular case on the webpages I checked. Since I am trying to learn javascript just with internet tutorials, I tried to guess the solution as good as I could!
And in case it’s correct (sort of) or that the correct version is very similar, I cannot understand how I should advance in the array while I create new cars. For example, if I run it once, the first car created will receive the information on the position [0], but if I run it twice or more times… how can I know in which position of the array I should find the information?
I am quite confused with this subject. I will be very grateful if someone can give me some advice. In the meantime, I continue reading about it, to see if I find out something else.
Thanks!
If I understand correctly you want to create a new car object for as many brands in the array. The first thing is to fix your constructor. Note that constructors are capitalized as a convention and the prototype should be declared outside, but you don’t need the prototype because you’re dealing with unique properties not shared methods. Then you can pass 2 parameters that will be assigned to the properties. In other words:
If you need a method to read those properties add it to the prototype like:
Finally, to create a new car for every item in the array you’d do it like this:
Now you have 4 cars in the
carsarray, and each car will be a different brand and color.But better yet, you can organize your brands and colors in an object and a
for...into create new cars: