Problem to do an arrays exercise. Beginner inside - javascript

I'm learning Javascript, and I have a problem with arrays in Javascript, and I have to do a class called TV Show with title, thematicand and actors (actors with array) Then, I have to do a function to grab a specific actor and classify it as "favorite" randomly.
Once done, I get an "empty" array.
This is my code.
class TVShow {
constructor (title, thematic, principalActors){
var arrayActors = new Array();
this.title=title;
this.thematic=thematic;
principalActors=[];
this.generateFavActor = function(){
var long = principalActors.lenght;
let calc = Math.floor(Math.random()*(long));
arrayActors = principalActors[calc];
}
console.log(arrayActors);
}
}
var show01= new TVShow("The Revolution", "Accion",["Hello","Hello2"]);
show01.generateFavActor();
var show02 = new TVShow("Peaky Blinders", "Drama",["Hello","Hello2", "Hello3"] );
show02.generateFavActor();
var show03 = new TVShow ("Stranger Things", "Accion", ["Hello","Hello2", "Hello3", "Hello4"]);
show03.generateFavActor();
Thanks!!

that ? ( using Destructuring assignment )
class TVShow
{
constructor (title, thematic, principalActors)
{
this.title = title
this.thematic = thematic
this.actors = [...principalActors]
}
generateFavActor()
{
console.log( this.actors[ Math.floor(Math.random()*this.actors.length ) ])
}
}
var show01 = new TVShow('The Revolution', 'Accion', ['Hello','Hello2'])
, show02 = new TVShow('Peaky Blinders', 'Drama', ['Hello','Hello2', 'Hello3'] )
, show03 = new TVShow('Stranger Things', 'Accion', ['Hello','Hello2', 'Hello3', 'Hello4'])
;
show01.generateFavActor()
show02.generateFavActor()
show03.generateFavActor()

I think you want something like this:
class TVShow {
constructor (title, thematic, principalActors){
this.title=title;
this.thematic=thematic;
this.arrayActors = principalActors;
this.generateFavActor = function(){
var size = principalActors.length;
let calc = Math.floor(Math.random()*(size));
return principalActors[calc];
}
this.favoriteActor = this.generateFavActor();
}
}
var show01 = new TVShow("The Revolution", "Accion",["Hello","Hello2"]);
var fav01 = show01.favoriteActor;
var show02 = new TVShow("Peaky Blinders", "Drama",["Hello","Hello2", "Hello3"] );
var fav02 = show02.favoriteActor;
var show03 = new TVShow ("Stranger Things", "Accion", ["Hello","Hello2", "Hello3", "Hello4"]);
var fav03 = show03.favoriteActor;
console.log(fav01);
console.log(fav02);
console.log(fav03);

first correct the principalActors.length not principalActors.lenght
Second don't set principalActors as an empty array Next Just put console.log inside the function... it will give you the right answer...right now it is showing the value which is just assigned to an empty array var arrayActors = new Array() Hope it will be HelpFul :-) and I think arrayActors don'nt need to be an an array
class TVShow {
constructor (title, thematic, principalActors){
var arrayActors = new Array();
this.title=title;
this.thematic=thematic;
this.generateFavActor = function(){
var long = principalActors.length;
let calc = Math.floor(Math.random()*(long));
arrayActors = principalActors[calc];
console.log(arrayActors);
}
}
}
var show01= new TVShow("The Revolution", "Accion",["Hello","Hello2"]);
show01.generateFavActor();
var show02 = new TVShow("Peaky Blinders", "Drama",["Hello","Hello2", "Hello3"] );
show02.generateFavActor();
var show03 = new TVShow ("Stranger Things", "Accion", ["Hello","Hello2", "Hello3", "Hello4"]);
show03.generateFavActor();

Related

How to initialize an array of objects inside of another array of objects?

I have a question. How can I initialize my var ingredientes = []; inside of the object "receita"? Is it done like I did? Or do I have to initialize it inside instead of outside?
var receitas = [];
var ingredientes = [];
var ingrediente = {
constructor: function(aNome, aQuantidade){
this.nome=aNome;
this.quantidade=aQuantidade;
}
};
var receita = {
constructor: function(aTipo, aNome, aTempo, aCusto, aDificuldade,
aDescricao, aIngredientes){
this.nome=aNome;
this.tipo=aTipo;
this.tempo=aTempo;
this.custo=aCusto;
this.dificuldade=aDificuldade;
this.descricao=aDescricao;
this.ingredientes=aIngredientes;
}
}
Thanks for any response!
I guess what you're actually looking for are classes, try doing this;
var receitas = [];
var ingredientes = [];
class Receita {
constructor(aTipo, aNome, aTempo, aCusto, aDificuldade, aDescricao, aIngredientes) {
this.nome = aNome;
this.tipo = aTipo;
this.tempo = aTempo;
this.custo = aCusto;
this.dificuldade = aDificuldade;
this.descricao = aDescricao;
this.ingredientes = aIngredientes;
}
}
class Ingrediente {
constructor(aNome, aQuantidade) {
this.nome = aNome;
this.quantidade = aQuantidade;
}
}
So to add an ingrediente to the ingredientes array you should do something like this:
var newReceita = new receita('Bolo', 'Bolo de fubá');
ingredientes = [
new ingrediente('Farinha', 300),
new ingrediente('Ovos', 2)
]
receita.ingredientes = ingredientes;
receita.constructor(...) will create all the properties within receita.

How to get the total number of objects created in javascript for a class?

Lets say I have the following code snippet:
function Airplane(id) {
this.id = id;
}
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
Is there any way to get the total number of Airplane objects created something like Airplane.getCreatedLength()?
You could keep track of those in a property attached to the constructor:
function Airplane(id) {
this.id = id;
Airplane.instances += 1;
}
Airplane.instances = 0;
var air1 = new Airplane(234);
var air2 = new Airplane(235);
var air3 = new Airplane(236);
console.log(Airplane.instances) // 3

How to push a value in an array

i want to know how can i store data in an array like that in order to do it with push function.
here is the code
var data_array = [];
and data look like that
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
any help to change this way of inserting and use push function .
May be this will help,
You can loop through all the keys of the object and push each one into the array
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var keysArray = Object.keys(my_data);
keysArray.forEach(function(key, index) {
data_array.push({ key : my_data[key]});
});
console.log(data_array);
Try this (wrap data in curly braces):
data_array.push( {"2011":{"name":"Team Leaders","total":93,"drilldown":"true"} })
I don't know Exactly what do you want. Anyway, I think that It works for you.
var personInfo = new Object();
var my_data = new Object();
personInfo.name = 'Team Leaders';
personInfo.total = 93;
personInfo.drilldown = 'true';
my_data.person1 = personInfo;
my_data.person2 = personInfo;
// confirm
var jsonType = JSON.stringify(my_data);
console.log(jsonType);
I think this is what you need
var data_array = [];
var my_data = {
"2011":{"name":"Team Leaders","total":93,"drilldown":"true"},
"2012":{"name":"Agents","total":1997,"drilldown":"true"},
"2013":{"name":"Coachs","total":1188,"drilldown":"true"},
"2014":{"name":"Formateurs","total":1188,"drilldown":"true"},
"2015":{"name":"Quality Analysts","total":1188,"drilldown":"true"}
};
var data_keys= Object.keys(my_data);
data_keys.forEach(function(key, index) {
var obj = {};
obj[key] = my_data[key];
data_array.push(obj);
});

Having trouble with image preload code

I have this object constructor function that has a preload method for preloading
rollover images pairs.
So, I have two questions:
1: why is the alert dialog just doing 'STR: ' with no data attached? (this type of problem is generally due to my blindness.
2: is it possible to treat the this.buttons_on and this.buttons_off as objects in that instead of
a numerical index, use a sting index so the rollover event handler does not need to loop through
the buttons_on and buttons_off arrays to get the one that should be swapped out;
function _NAV()
{
this.list_off = [];
this.list_on = [];
this.buttons_on = [];
this.buttons_off = [];
this.buttons_all = {}; // .on and .off
this.button_events = {};
this.img = true;
this.img_ids = {}
this.preLoad = function()
{
if(document.images) //creates image object array for preload.
{
var STR = '';
for(var i = 0; i < list_off.length; i++)
{
var lab_on = list_on[i].replace('\.jpg', '');
var lab_off = list_off[i].replace('\.jpg', '');
STR += lab_on+'||'+lab_off+"\n";
this.buttons_on[i] = new Image();
this.buttons_on[i].src = srcPath+list_on[i];
this.bottons_on[i].id = img_ids[i];
this.buttons_off[i] = new Image();
this.buttons_off[i].src = srcPath+list_off[i];
this.buttons_off[i].id = img_ids[i];
}
alert("STR: "+STR);
}
else
{
this.img = false
}
}
//// ...etc...
Here is the call before the onload event fires
var rollover = new _NAV();
rollover.preLoad();
Here are the arrays used
var srcPath = '../nav_buttons/';
var list_off = new Array(); // not new Object;
list_off[0] = "bio_off.jpg";
list_off[1] = "cd_off.jpg";
list_off[2] = "home_off.jpg";
list_off[3] = "inst_off.jpg";
list_off[4] = "photo_off.jpg";
list_off[5] = "rev_off.jpg";
list_off[6] = "samp_off.jpg";
var list_on = new Array();
list_on[0] = "bio_on.jpg";
list_on[1] = "cd_on.jpg";
list_on[2] = "home_on.jpg";
list_on[3] = "inst_on.jpg";
list_on[4] = "photo_on.jpg";
list_on[5] = "rev_on.jpg";
list_on[6] = "samp_on.jpg";
var img_ids = new Array();
Thanks for time and attention.
1:
Try PHPGlue's suggestion and add this. in front of all your member variables (this.list_on, this.list_off, this.img_ids)
You also have a typo on one line. bottons_on is misspelled.
this.bottons_on[i].id = img_ids[i];
2:
Yes, you can use a string as an index. Just make buttons_on and buttons_off objects instead of arrays.
function _NAV()
{
this.buttons_on = {};
this.buttons_off = {};
// For example:
this.buttons_off[lab_off] = new Image();
}

Populating 2D Array in JS

I am trying to popoulate a 2D array using Firebug API,
var sites = [];
var siteCounter = 0;
//Firebase API Calls
var messageListRef = new Firebase('https://my.firebaseio.com');
messageListRef.once('value', function(allMessagesSnapshot) {
allMessagesSnapshot.forEach(function(messageSnapshot) {
var latitude = messageSnapshot.child('latitude').val();
var longitude = messageSnapshot.child('longitude').val();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
siteCounter++;
alert(sites[siteCounter][1] + " " + sites[siteCounter][2] );
});
});
But this breaks for sites[siteCounter][0] and says it is undefined. Any clue how to work with this ?
if you want 2D array, you must to initialize like this :
var tab = new Array();
after
tab[0] = new Array();
Try this code
sites[siteCounter] = new Array();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
or directly
sites[siteCounter] = new Array("siteCounter", latitude, longitude, siteCounter, "This is siteCounter.");
Have you tried to do a
sites[siteCounter] = [];
before sites[siteCounter][0]?
I assume you have to declare it as an array to be able to put stuff in the array.

Categories

Resources