declaring more than 10 objects - javascript

as we know we can declare an array like this
for (int i=0;i<array.length;i++)
{ d[i]=new array();}
What about an object I want to declare more than 10 objects and I think it's not efficient to
write a declare statements for 10 times !!like this
car c1 = new car();
car c2= new Car();
..etc
what can I do ?

You are mixing the things a little.
var array = [];
for (var i = 0; i < 10; i++)
{
array[i] = new Car();
}
As Daniel noted, you can even use Array.push() in this way:
var array = [];
for (var i = 0; i < 10; i++)
{
array.push(new Car());
}
The point is that you declare the array with var array = [] (or with var array = new Array(), see the differences here What’s the difference between "Array()" and "[]" while declaring a JavaScript array?) and you set the items at the index you want (in Javascript arrays are dynamicly sized)

Use an array of objects like:
var cars = [];
for (var i = 0; i < 10; i++) {
cars.push(new Car());
}

Hum, what you're doing in your first example is declaring an array of array. To create an array, simply do
var a = [];
To create and maintain many objects, put them in that array:
for(var i = 0; i < 10; i++)
a[i] = new Car();
car[0].drive(); //Drive first car

You can:
use eval (it was designed for things like this)
use an array of objects
for (var i=1,n=3; i<n; i++)
eval("c" + i + "= new Car()");
var a = [];
for (var i=1,n=3; i<n; i++)
a[i] = new Car();

Related

Looping all objects in an array

I have an array of data as follows:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]]
I tried to write datas to console for each object as follows, but it does not work:
for (var i = 0; i < 3; i++) {
for(var obj in Sonuc[i]) {
console.log(obj.Number);
};
}
How can I output the Number value for each data on console?
The problem is that you have an array or arrays, with the sub-arrays each containing one or more objects.
Your problem is you are not specifying the index for the sub-arrays. You can access the first object like this:
console.log(obj[0].Number);
That will get you some output at at least, but it is confusing exactly what data you want to get. That 3 loop makes no sense...
If you want to output all objects, then you should first loop the sub-arrays, and then loop the objects. Something like this:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]];
for (var i = 0; i < Sonuc.length; i++) {
var arr = Sonuc[i];
for (var j = 0; j < arr.length; j++) {
var obj = arr[j];
console.log(obj.Number);
}
}

Array is overwriting previous object

I am creating an object with my XML data and pushing into the array. But when it coming out from the method I can see all the array value is copy of first one. Can anyone help me.
Here is my code :
var obj = {};
for(var i = 1; i < myData.length; i++) {
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++){
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}
You need to create a new object in the top level for loop. In your case you have only one variable, for which you are adding properties and push into the array it's reference. So at the end you have one big object and pushed the reference of it into the array for many times.
for(var i = 1; i < myData.length; i++) {
var obj = {};
var myDAtt = myData[i].getElementsByTagName('D');
for(var j = 0; j < myDAtt.length; j++) {
obj[myDAtt[j].getAttribute('dataIndex')] = myDAtt[j].getAttribute('V')
}
me.Rec.push(obj);
}

Why do I have to make a seperate variable to correct this loop? (Javascript Basics)

I am currently learning Javascript so I will try my best with my choice of words.
In the following code below.
I want the variable "allFoods" to display all the different variations.
Although, I have found a loophole, I like to understand the logic and why things are done rather than memorizing code.
>1 var fruits = ["apples", "pears"];
>2 var junk = ["twinkies", "pizza"];
>3 var allFoods = [];
for (var i = 0; i < fruits.length; i++) {
for (var j = 0; j < junk.length; j++) {
allFoods = fruits[i] + junk[i];
alert(allFoods);
Instead, of the variable "allFoods" returning all the different variations..
applestwinkies, applespizza, pearstwinkies, pearspizza
It returns this...
applestwinkies, applestwinkies, pearspizza, pears,pizza
The loophole i found is...
>1 var fruits = ["apples", "pears"];
>2 var junk = ["twinkies", "pizza"];
>3 var allFoods = [];
>4 var b = 0;
>5 for (var i = 0; i < fruits.length; i++) {
>6 for (var j = 0; j < junk.length; j++) {
>7 allFoods[b] = fruits[i] + junk[i];
b++;
>8 alert(allFoods);
Although it is working. I have no idea what is going on and why it's working!
You have an error on this line:
allFoods = fruits[i] + junk[i];
Change it to:
allFoods = fruits[i] + junk[j];
^ use index j here
When you're adding elements to an array, you can do it multiple ways.
var arr = [];
arr.push("One"); // Pushes a new element into the array
arr[1] = "Two"; // Sets a specific element in the array
// arr === ["One","Two"]
The plus operator + provides different functionality depending on the context. When used with string values, it will concatenate the strings together. Thus allFoods = fruits[1] + junk[1]; is equivalent to allFoods = "pearspizza";
What you'd want to do is loop through the arrays individually and use the push method to append elements to the new array, as in the following code example:
var fruits = ["apples", "pears"];
var junk = ["twinkies", "pizza"];
var allFoods = [];
for (var i = 0; i < fruits.length; i++) {
allFoods.push(fruits[i]);
}
for (var j = 0; j < junk.length; j++) {
allFoods.push(junk[j]);
}
alert(allFoods);
Of course, you could also use the Array object's concat() method to join two arrays into one.
var fruits = ["apples", "pears"];
var junk = ["twinkies", "pizza"];
var allFoods = fruits.concat(junk);
alert(allFoods);

How to create a multidimensional array in JavaScript?

How can I create a multidimensional array in JavaScript?
I have:
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar = [];
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
If I do:
groupsData.name_of_bar[0]
I get errors:
TypeError: Cannot read property '0' of undefined
TypeError: Cannot set property 'a' of undefined
What am I doing wrong?
JavaScript doesn't support multidimensional arrays per se. The closest you can come is to create an array where the values in it are also arrays.
// Set this **outside** the loop so you don't overwrite it each time you go around the loop
groupsData.name_of_bar = [];
for (var i = 0; i < m; i++){
// Create a new "array" each time you go around the loop
// Use objects, not arrays, when you have named properties (instead of ordered numeric ones)
groupsData.name_of_bar[i] = {};
groupsData.name_of_bar[i]['a'] = data[i].a;
groupsData.name_of_bar[i]['ab'] = data[i].ab;
groupsData.name_of_bar[i]['de'] = data[i].de;
groupsData.name_of_bar[i]['gh'] = data[i].gh;
groupsData.name_of_bar[i]['xy'] = data[i].xy;
}
Each iteration through the loop, you are doing groupsData.name_of_bar = [];. This removes whatever else is already in there and replaces it with a blank array.
Also, when you do groupsData.name_of_bar[i]['a'], you need to create groupsData.name_of_bar[i] first.
A way to do this is:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy: data[i].xy,
});
}
Note that in JavaScript, arrays can only be numerically indexed. If you want string indexes, you need to use an object.
Also, if there are no other values in data[i], then you can simplify this even further by doing:
groupsData.name_of_bar = [];
var m = 4;
for (var i = 0; i < m; i++){
groupsData.name_of_bar.push(data[i]);
}
Heck, why not just use groupsData.name_of_bar = data; and lose the loop altogether?
The way you are declaring your objects are a little off. It looks like you are attempting to create an array of objects.
var groupsData = {name_of_bar: []},
m = 4,
i = 0;
for(; i < m; i++) {
groupsData.name_of_bar.push({
a: data[i].a,
ab: data[i].ab,
de: data[i].de,
gh: data[i].gh,
xy = data[i].xy
});
}

Creating array of objects dynamically based on length

I have the length of my previous object and i need to create a new array of objects based on the length with new key's.
Length = 3;
var newArray = [];
for(var i =0; i <3; i++){
var Object = {};
Object['newKey'] = 1;
newArray.push(Object);
}
This would eventually create newArray of Objects whose length is 3 containing something like this.. newArray[0],[1],[2].
Am i doing this correctly, please do suggest me if anything wrong or a better way to do this.
Here's what you wrote (I think), just shortened a bit (and fixed the capitalization of variable names)
var length = 3;
var newArray = [];
for( var i = 0 ; i < length ; i++ ) {
newArray.push({newKey: 1});
}
but to be honest it's unclear to me exactly what you're trying to accomplish
You could make it slightly more dynamic by referencing the variable for length.
Example updated per comments:
var length = 3,
newArray = [];
for ( var i=0; i<length; i++ ) {
var tempObj = {};
tempObj['newKey'] = 'SomeValue';
newArray.push(tempObj);
}
I didn't really do more than clean up what you have.

Categories