Create several instances of a module with different values - javascript

This is probably a simple problem but I need to create the JavaScript equivalent to N instances of a 'class' whose state must be totally separate.
like:
var car = new Car('Ford');
var car = new Car('Toyota');
How can I achieve this?

You can use an array object to store them:
var cars = [];
cars.push(new Car('Ford'));
cars.push(new Car('Toyota'));
cars[0].beep();
You can iterate over all the stored instances using a for loop:
for (var i = 0; i < cars.length; i++) {
var car = cars[i];
car.beep();
}

It if very difficult to see what the problem is here.
From your code snippet I can see the only problem that you may have in creating new instances is that you'r giving it a the same name.
Give it some other var name:
var ford = new Car('Ford');
var toyota = new Car('Toyota');
Otherwise if you have an array of different makes and want to convert it into an array of car objects you can do this:
var types = ["Ford", "Toyota", "VW", "renault"];
var cars = {};
for (var i = 0; i != types.length ; i++)
cars[types[i]] = new Car(types[i]);
You can access these cars like this:
var ford = cars.Ford;
or like this:
var ford = cars["Ford"];

Related

Naming objects inside of an array dynamically

I'm quite new to JavaScript and programming in general and figured I'd hone my abilities by working on a small project. The idea is that I have a form for information on an event, an input for the name, date, time and a small thumbnail image.
I want each event to be an object inside of an array, so I would have something like:
var concerts = {};
for (var i = 1; i < 11; i++) {
window["concert"+i] = new Object();
}
and the array would end up being something:
var concerts = [concert1, concert2, concert3]
and so on.
How could I get this loop to work so that it would take the 3 parameters and create a new object in the array named 'concert'+i? Thanks for reading!
Concerts must be an array:
var concerts = [];
for (var i = 0; i < 10; i++) {
concerts[i] = {
//maybe also giveit a name if you want to:
name:"concert"+i
};
}
You can access it like this:
concerts[0].name="Wacken";//first concert...
Note that this:
window["concert"+i] = new Object();
is very bad style...
First you declare a variable concerts of type object. But you want an array. That first line makes your code very confusing.
You have to start with an empty array:
var concerts = []; // alternatively: new Array();
In the end you'd like to have a structure like this:
[
{ /* object 1 */ },
{ /* object 2 */ }
]
Now you can run a foor-loop and populate the array:
for (var i = 0; i <= 10; i++) {
concerts.push({['concert' + i]: {}});
}
This will return something like:
[
{'concert0': {}},
{'concert1': {}},
// skipped
{'concert10': {}}
]
Later you can populate the objects. This is however not a very nice style. Maybe you should reconsider if it is really necessary to give a name to every object like concert0...10.
Go rather for:
var concerts = [
{
'name': 'concert0',
'location': 'somewhere'
}
// continue with other objects
];

Putting an object into an array in JavaScript

I'm currently working with an MVC JS framework and I want to be able to get a list of objects that I can take a random entry out of on a loop. So far I've managed to create a function that finds a random ID and pulls out that object so that part is not a problem. It's what is going into the array of objects:
QuestionsSetup: function(gameType) {
// Setup Resources
var c = this.View.children;
var player1qs = [];
var leftQ = 0;
var rightQ = 0;
var maxQValue = 50;
var minQValue = 1;
// Fill array with questions
for (var i = 0; i < 5; i++) {
// Build a random question with numbers between 1 and 50
// Build Question Text to output to user
// Generate correct answers based on generated question
// Generate unsorted, incorrect answers and add them to an array
//Place Questions into object
questions.qId = i;
questions.leftQ = leftQ;
questions.rightQ = rightQ;
questions.correctAnswer = correctAnswer;
questions.allAnswers = sortedAnswers;
questions.questionText = questionText;
//Add to array of questions
player1qs.push(questions);
}
}
This does add them to an array but when adding a new object it also changes the values of the existing objects in the array so they all come out the same no matter which one I pull out later. The questions object is declared in it's own file in a models folder. Is there any way, at the start of each loop, to tell the application I want new empty questions object as opposed to referencing the existing ones? I know that you can in similar back end languguages so I refuse to beleive that something so simple doesn't exist in JavaScript too?
Declaring a variable for each array item is definitely missing.
QuestionsSetup: function(gameType) {
// Setup Resources
var c = this.View.children;
var player1qs = [];
var leftQ = 0;
var rightQ = 0;
var maxQValue = 50;
var minQValue = 1;
// Fill array with questions
for (var i = 0; i < 5; i++) {
var tempQuestion = {
qId: i,
leftQ: leftQ,
rightQ: rightQ,
correctAnswer: correctAnswer,
allAnswers: sortedAnswers,
questionText: questionText
}
// ...
//Add to array of questions
player1qs.push(tempQuestion);
}
}
Using a separate closure inside a loop also might be a good idea.
do this:
for (var i = 0; i < 5; i++) {
let questions = {};
// the rest....
you need to define the object first.
Maybe you should just initialize the questions object before initializing its properties, so the code should look like this:
//Place Questions into object
questions = {};
questions.qId = i;
questions.leftQ = leftQ;
questions.rightQ = rightQ;
questions.correctAnswer = correctAnswer;
questions.allAnswers = sortedAnswers;
questions.questionText = questionText;
//Add to array of questions
player1qs.push(questions);

Create variables based on array

I have the following array and a loop fetching the keys (https://jsfiddle.net/ytm04L53/)
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
alert(feed.match(/\d+$/));
}
The array will always contain different number of keys, What I would like to do is either use these keys as variables and assign the value after the : semicolon as its value or just create a new set of variables and assign the values found on these keys to them.
How can I achieve this? so that I can then perform some sort of comparison
if (test_user > 5000) {dosomething}
update
Thanks for the answers, how can I also create a set of variables and assign the array values to them? For instance something like the following.
valCount(feeds.split(","));
function valCount(t) {
if(t[0].match(/test_user_.*/))
var testUser = t[0].match(/\d+$/);
}
Obviously there is the possibility that sometimes there will only be 1 key in the array and some times 2 or 3, so t[0] won't always be test_user_
I need to somehow pass the array to a function and perform some sort of matching, if array key starts with test_user_ then grab the value and assign it to a define variable.
Thanks guys for all your help!
You can't (reasonably) create variables with dynamic names at runtime. (It is technically possible.)
Instead, you can create object properties:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":"); // Splits the string on the :
obj[parts[0]] = parts[1]; // Creates the property
});
Now, obj["test_user_201508_20150826080829.txt"] has the value "12345".
Live Example:
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
var obj = {};
feeds.forEach(function(entry) {
var parts = entry.split(":");
obj[parts[0]] = parts[1];
});
snippet.log(obj["test_user_201508_20150826080829.txt"]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
You can do it like this, using the split function:
var i;
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
for (i = 0; i < feeds.length; i++) {
var feed = feeds[i];
console.log(feed.split(/[:]/));
}
This outputs:
["test_user_201508_20150826080829.txt", "12345"]
["test_user_list20150826", "666"]
["test_list_Summary20150826.txt", "321"]
Use the split method
var feeds = ["test_user_201508_20150826080829.txt:12345","test_user_list20150826:666","test_list_Summary20150826.txt:321"];
feedMap = {}
for (i = 0; i < feeds.length; i++) {
var temp = feeds[i].split(':');
feedMap[temp[0]] = temp[1];
}
Yields:
{
"test_user_201508_20150826080829.txt":"12345",
"test_user_list20150826":"666",
"test_list_Summary20150826.txt":"321"
}
And can be accessed like:
feedMap["test_user_201508_20150826080829.txt"]
Here is a codepen
it is not very good idea but if you really need to create variables on-the-run here's the code:
for (i = 0; i < feeds.length; i++)
{
var feed = feeds[i];
window[feed.substring(0, feed.indexOf(":"))] = feed.match(/\d+$/);
}
alert(test_user_201508_20150826080829)
Of course you cannot have any variable-name-string containing banned signs (like '.')
Regards,
MichaƂ

Creating Objects inside objects using a Constructor

In the below code I am trying to create an object named "portfolio" inside which
I want to create other objects that contain the properties "stockvalue" and "price"?
var portfolio_create = function(stock,stockvalue,price)
{
for(i in stock)
{
this[stock[i]] = stock[i];
this[stock[i]]["stockvalue"] =stockvalue[i];
this[stock[i]]["price"]=price[i]
}
}
var portfolio = new portfolio_create(["ibm","tcs"],[23,34],[34,45]);
var stock_market = portfolio;
alert(portfolio["ibm"]["stockvalue"]); // undefined
Why does the alert return "undefined" and not 23?
Thnaks in advance.
var portfolio_create = function (stock, stockvalue, price) {
for (var i = 0, len = stock.length; i < len; i++) {
this[stock[i]] = {};
this[stock[i]]["stockvalue"] = stockvalue[i];
this[stock[i]]["price"] = price[i];
}
}
var portfolio = new portfolio_create(["ibm", "tcs"], [23,34], [34,45]);
Don't use for..in for arrays.
this[stock[i]] = stock[i]; replace to this[stock[i]] = {};.
Example
I think there is a little confusion here, between objects and variables.
You can create a real JavaScript class portfolio, which contain a collection of another class stock, which contain 2 variables value and price.
In your portfolio class, you can add a AddStock methode, and a GetStock.
Look at JavaScript Classes, I think you will find your hapiness.
Steeve
And try to use libs like underscore or lodash to get rid of these for loops (each). It is much nicer and more functional.
A little bit shorter:
this[stock[i]] = { stockvalue: stockvalue[i], price: price[i] };

How do I copy a foundset?

So I have the following issue:
I have a Foundset with a bunch of records, and I'd like to (deep) copy them to a new location, including all values but without the IDs. What's the best way to do this?
If you want to do an deep copy of an foundset you need the follow steps:
Create an empty foundset over retrieveOrCreateFoundset()
iterate over all records of the foundset, that should copied to a new one
get the dataProviders with something like rec.dataprovider()
get the value of each dataprovider on a record rec.value()
be sure that the uuid dataprovider isnt copy to the new Record
set the values to a the new record over the dataproviders
persist the changes
Full code example would be:
var vMobileController = plugins.iBizClientWebService.mobileController();
var vFoundset = vMobileController.currentFoundset();
var vDatabaseManager = vMobileController.dataManager();
var copyFoundSet = vDatabaseManager.retrieveOrCreateFoundset("<datasource>:<label>");
for (var index = 0; index < vFoundset.size(); index++) {
var rec = vFoundset.record(index);
var loc = copyFoundSet.newRecord();
var newRecord = copyFoundSet.record(loc);
var allDataproviders = rec.dataprovider();
for(var i=0;i<allDataproviders.length;i++)
{
var dataProvider = allDataproviders[i];
var dataValue = rec.value(dataProvider);
if(dataProvider != "attribute_id")
{
newRecord.setValue(dataProvider, dataValue);
}
}
}
copyFoundSet.saveData();

Categories

Resources