Not understanding how to load class properties from an array - javascript

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:
function Car( brand, color ) {
this.brand = brand;
this.color = color;
}
If you need a method to read those properties add it to the prototype like:
Car.prototype = {
loadInfo: function() {
alert( this.brand +':'+ this.color );
}
};
Finally, to create a new car for every item in the array you'd do it like this:
var cars = [];
for ( var i = 0; i < brand.length; i++ ) {
cars.push( new Car( brand[i], color[i] ) );
}
Now you have 4 cars in the cars array, 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...in to create new cars:
var cars = {
Audi: 'red',
Ford: 'black',
Peugeot: 'black',
Nissan: 'white'
};
var mycars = [];
for ( var c in cars ) {
mycars.push( new Car( c, cars[c] ) );
}

Related

How can I parse a JSON object containing a colon

I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)

How would I store and retrieve an array of objects in localStorage?

My question is regarding using localStorage for a page. I've been making a game in JavaScript, and as it's quite a lengthy one to play, one problem has been that too often the tab is accidentally closed or the computer shut down before its completion. Therefore, I'm hoping to work out some sort of simple game save procedure so that such events will not cause the whole game to reset.
The data that I need to store consists of three arrays and one primitive value. Each of these are created when the user begins playing the game, and as the game is played, objects will be added to the arrays, and the primitive value- an integer- is incremented. The integer value should not be difficult, but the arrays consist of objects, rather than primitive values, and so JSON.stringify only literally returns "[object Object, object Object, object Object (...)]" as a string.
I've tried iterating over the arrays and stringifying each of the objects individually, but that seems sort of convoluted, I can't quite think round it, and besides, I seem to have done something wrong and it doesn't work regardless.
Here is the relevant moiety of the program thus far, if anyone wants to see for whatever reason:
var frogarray = [parent1, parent2, parent3, parent4]
var nestarray = [nest1]
var genesisarray = [];
pushGenesis( new Genesis() );
var boondollars = 0;
function getProgress () {
var frogdata = localStorage.getItem("frogs");
var nestdata = localStorage.getItem("nests");
var boondata = localStorage.getItem("boondollars");
var genesisdata = localStorage.getItem("genesis");
frogarray = JSON.parse( frogdata );
nestarray = JSON.parse( nestdata );
genesisarray = JSON.parse( genesisdata );
boondollars = boondata;
frogtoUI();
nesttoUI();
printboons();
}
function saveProgress() {
var storagefrog = [];
var storagenest = [];
var storagegenesis = [];
function stringifying ( array, name, storagearray ) {
for ( i = 0; i < array.length; i++ ) {
var s = JSON.stringify( array[i] );
storagearray.push(s);
localStorage.setItem(name, JSON.stringify(storagearray));
}
}
stringifying(frogarray, "frogs", storagefrog)
stringifying(nestarray, "nests", storagenest)
stringifying(genesisarray, "genesis", storagegenesis)
localStorage.setItem("boondollars", boondollars)
}
Is there any way that I can retrieve and store arrays of objects in localStorage correctly- a simpler or cleaner way, if possible?
Edit:
Here's an example of an object from each array:
frogarray or genesisarray:
parent1 = {
gender: "female",
colour: "red",
eyecolour: "blue",
pattern: "plain",
sized: "small",
}
nestarray:
nest1 = {
typ: "normal",
nestTime: 0,
frog1: "",
frog2: "",
currentbreed: false,
}

People guesser program with JavaScript objects

I'm trying to learn JavaScript, and so I'm doing this project to practice. I'm trying to figure out how the objects and all that work. Basically what I want, is a list of people, as objects, with certain properties assigned to each. Then it to ask a bunch of questions until it guesses the person you're thinking of. I've searched around, but can't really find exactly how to do this. This is what I have so far:
function person(name,age,eyecolor,gender,eyeglasses)
{
this.name=name;
this.age=age;
this.eyecolor=eyecolor;
this.gender=gender;
this.eyeglasses=eyeglasses;
}
var Dad=new person("Dad",45,"blue","male",true);
var Mom=new person("Mom",48,"blue","female",false);
var Brother=new person("Brother",16,"blue","male",false);
var Sister=new person("Sister",15,"green","female",false);
function askQuestion (){
}
function begin(){
askQuestion();
}
Now what I want is a way that I can, in the askQuestion function, select a question from a list based on what we know so far about the person. And then recalculate who of the people it could be, and then pick another question to ask, until we know who it is. Hopefully I've made this clear. How would I do that?
This is a bit like the game "Guess Who?" no? Alright so this is what you do:
First you create a constructor for a person. You got this right.
function Person(name, age, eyecolor, gender, eyeglasses) {
this.name = name;
this.age = age;
this.eyecolor = eyecolor;
this.gender = gender;
this.eyeglasses = eyeglasses;
}
Then you create list of possible people. A list means an array.
var people = [
new Person("Dad", 45, "blue", "male", true),
new Person("Mom", 48, "blue", "female", false),
new Person("Brother", 16, "blue", "male", false),
new Person("Sister", 15, "green", "female", false)
];
Then you keep asking questions to guess who the person is. To keep asking means to use a loop. We'll keep looping until there's only one person left in the list (the person we're looking for):
while (people.length > 1) askQuestion();
Next we define the askQuestion function. First we need to select what question to ask. So we make a list of questions. Again this is an array. We'll also store which property to test and the result for true and false conditions.
var questions = [
["eyecolor", "blue", "green", "Does the person have blue eyes?"],
["gender", "male", "female", "Is the person a male?"],
["eyeglasses", true, false, "Does the person wear eyeglasses?"]
];
These three questions are all you need to know to determine who the person is. Next we record which question is currently being asked (0, 1 or 2).
var question_no = 0;
Finally we ask the questions to determine who the person is:
function askQuestion() {
var question = questions[question_no++];
var answer = confirm(question[3]) ? question[1] : question[2];
var predicate = question[0];
people = people.filter(function (person) {
return person[predicate] === answer;
});
}
Here we ask the user a question, determine which answer he chose and use that information to filter the people who match the given description. Finally we end up with one person:
alert("The person you're thinking about is " + people[0].name + ".");
See the working demo here: http://jsfiddle.net/9g6XU/
Here's how I would do it. It's shorter than Aadit's answer, and in my opinion, simpler and easier to understand.
Make a list of the people. Use an array literal:
var people = [Dad, Mom, Brother, Sister];
I like to structure my code, so I would put the questions in an object:
var questions = {
"Are they male or female?" : 'gender',
"What is their eye color?" : 'eyecolor',
"Do they wear glasses?" : 'eyeglasses'
};
This could be expanded with as many properties as you want.
Then:
for (question in questions) { //This is how you loop through an object
var property = questions[question]; //This gets the second part of the object property, e.g. 'gender'
var answer = prompt(question);
//filter is an array method that removes items from the array when the function returns false.
//Object properties can be referenced with square brackets rather than periods. This means that it can work when the property name (such as 'gender') is saved as a string.
people = people.filter(function(person) { return person[property] == answer });
if (people.length == 1) {
alert("The person you are thinking of is " + people[0].name);
break;
}
if (people.length == 0) {
alert("There are no more people in the list :(");
break;
}
}
And I, too, made you a fiddle.Here it is.

.push() multiple objects into JavaScript array returns 'undefined'

When I add items to the beats array and then console.log the User, I'm getting the correct number of items in the array. But when I check .length, I always get 1.
Trying to call the index will always give me 'undefined' like so:
Tom.beats[1]
I think I'm missing something obvious, but this is beating me. I suspect that I'm misusing the .push method but I'm unsure. Any help is greatly appreciated!
(using Chrome dev tools)
//The USER
function User(name, role){
this.beats = [ ];
this.name = name;
this.role = role;
// add beats to beats array
this.addBeats = function(beats){
return this.beats.push(beats);
};
}
// Three New Instances. Three New Users.
var Mal = new User("Mal", "Rapper");
Mal.addBeats(["love", "cash"]);
var Dan = new User("Dan", "Producer");
Dan.addBeats(["cake", "dirt", "sally-mae"]);
var Tom = new User("Tom", "Producer");
Tom.addBeats(["Fun", "Little", "Samsung", "Turtle", "PC"]);
// Check for position in beats array
console.log(Tom.beats);
console.log(Mal.beats);
console.log(Dan.beats);
console.log(Mal.beats[1]);
console.log(Dan.beats[1]);
console.log(Tom.beats[1]);
Array.push(...) takes multiple arguments to append to the list. If you put them in an array itself, this very array of "beats" will be appended.
Array.concat(...) is most likely not what you are looking for, because it generates a new array instead of appending to the existing one.
You can use [].push.apply(Array, arg_list) to append the items of the argument list:
this.addBeats = function(beats) {
return [].push.apply(this.beats, beats);
};
Spread operator
In environments that support the spread operator you may now do the following:
this.addBeats = function (beats) {
return this.beats.push(...beats);
};
Or if you need more control for overwriting etc
this.addBeats = function(beats) {
return this.beats.splice(this.beats.length, null, ...beats);
};
addBeats() should concat this.beats with the beats parameter.

finding information inside of nested arrays

I have an array that stores the values:
var array = [['favorite color'],['black','red']]
to get black I would:
document.write(array[0][1][0]);
then if i append to the array another question [['favorite thing']['box','ball']]
If I wanted ball I would:
document.write.array[1][1][1];
I am having trouble understanding arrays. I want an array with one question and multiple answers then I want to loop through them and display everything. I can do the loop but I am unsure how to find things in nested arrays once I create them.
Use a combination of objects (which work like dictionaries) and arrays. For example:
var array = [
{'question' : 'favorite color', 'choices' : ['black','red'] },
{'question' : 'favorite thing', 'choices' : ['box','ball'] }
]
for( var i = 0; i < array.length; i++ ) {
var question = array[i]['question'];
var choices = array[i]['choices'];
// here you can display / write out the questions and choices
}
Bearing in mind, creating a class and using a constructor or init methods would probably be better to encapsulate the idea of questions and answers. But the above is the basic idea.
var array = [['favorite color'],['black','red','blue']];
document.writeln(array[1][1]);
document.write(array[1][2]);
​
Would print red then blue see it working live : http://jsfiddle.net/HJ872/
How?
array[0] => gets an *array* = ['favorite color']
=> array[0][0] gets this first element `favorite color`
array[1] => also gets this array = ['black','red','blue']
=> and then [1][1] will get 'red', [1][2] will get `blue`

Categories