how to add properly the value of counter to a variable name - javascript

it can seems easy, but I'm little lost...
What I need is to add the counter value to a variable name.
for (var i=0; i<8; i++){
var upBt0; //this is the name in the first iteration
var upBt1; //this is the name in the second iteration
.
.
.
var upBt8; //this is the name in the last iteration
}
How can I do this properly?
Sorry, Daniel
EDIT:
for (var i=0; i<8; i++)
{
this.upBt = "upBt"+i;
this.upBt = new PL_Button().init("upBarButton"+i);
}
I create buttons...in particular 8 buttons...
And later, I need access to each of these buttons:
function (){
this.upBt1;
this.upBt1;
this.upBt3;
this.upBt6;
}
Hope have explained better.
EDIT 2:
Finally, I solved it using an auxiliar array of the class, where I pushed each object in each iteration. Each item of this array is a real reference to each object, so changed the item in the array, changes are also made in the corresponding object...
Hope have explained well.
Thanks for your help,
Daniel

You can use this, but it's ugly code...
for (var i=0; i<8; i++){
this["upBt" + i] = Object.create(null);
}

Use an array helped to me:
this._arrayButtons = {};
for (var i=0; i<8; i++)
{
this.upBt = new PL_Button().init("upBarButton"+i);
this.upBt.imgPath = "res/builder/"+upBarImgs[i];
.
.
.
this._arrayButtons[i] = this.upBt;
}
After, in one function, I can access to the content of the variables such as:
function refreshFrameAlpha(){
this._arrayButtons[3].alpha = 125;
this._arrayButtons[5].alpha = 225;
.
.
}
In this way, I can refresh alpha (p.e) of the object, because each item of the array is a reference to the corresponding object.

Related

Loading JSON array from API into another array in Javascript using a loop

I'm pretty new to programming in general but have the problem that my array keeps being overwritten in my for loop so when I print in to the console only the last set of data is showing. i.e the data in the array is overwritten each time.
I want to store all the details in an array so I can work with the data. I have tried to put an array into an array but keep getting errors.
for (var i = 0; i < collection.length; i++){
var dailyfxTech = [];
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
How can I append the data to the dailyfxTech array each time it loops so that it looks like ;
dailyFxTech {[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], [support], [trend.src]},
{[ccypair], [resistance], ...etc},
I later want to be able to reference the array to place the data in other parts of my site eg:
dailyFxTech[2,3] = the support of third ccy pair.
Thank you for your help.
Your issue is that each time the loop is running you are declariing a new array. Super simple fix. Just need to put the var dailyfxTech outside of your loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
console.log(dailyfxTech)
Declare var dailyFxTech outside of the for loop.
var dailyfxTech = [];
for (var i = 0; i < collection.length; i++){
dailyfxTech.push((collection[i].ccyPair), (collection[i].resistance), (collection[i].support), (collection[i].trend.src));
}
When you have the var declaration in the body of the for loop, the variable is re-allocated and the old value is trashed.

Javascript two dimensional array initialization

Meet with a really weird javascript problem. See my codes below:
function initBadScripts(controlArray) {
var scriptsLine = prompt("Please enter the bad scripts", "debug");
if (scriptsLine != null) {
var pattern = /;/;
var nameList = scriptsLine.split(pattern);
alert(nameList+" "+nameList.length);
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter][0]=true;
controlArray[counter][1]= new RegExp(nameList[counter],"g");
alert(controlArray[counter][0]);
}
}
alert("wtf!");
}
var controlArray = [[]];
initBadScripts(controlArray);
I defined a function, and call that function. A 2-dimensional array called 'controlArray' is defined with no value. Basically, the function check the user's input and use regular expression to make a 'namelist'. For example, if the user type in
ExampleOne;ExampleTwo
The function will create an array called 'nameList'
nameList=[ExampleOne,ExampleTwo];
Then I want to make a dynamical initialization of the 2-dimensional array called 'controlArray', according to the length of nameList. However this only works fine the nameList'length is 1. If it exceeds one (the user type in 'ExampleOne;ExampleTwo'), the ExampleTwo does not go into the array, and the
alert("wtf");
doesn't run at all. This seems that there is already an error before it. Any comments?
JavaScript doesn't have a true 2-dimensional array. Rather, you're putting a second array inside the first array. Change it to this:
...
for(var counter = 0; counter < nameList.length; counter++){
controlArray[counter] = [true, new RegExp(nameList[counter],"g")];
...
Yes or you declare your variable like that:
var controlArray = [[],[]];
or
var controlArray = new Array(2);
for (var i = 0; i < 2; i++) {
controlArray[i] = new Array(2);
}

Filling an array with objects in Javascript

Currently I have an issue with filling an array which I call input in my code with the object which I call athlete in my code.The object which is called athlete is instantiated using several other arrays. I have attached a jsfiddle link to this post which is basically a simplified version with the same issue. I know the logic might look redundant but that is because it is necessary for this example(the actual logic will work with user input).
My issue is that I am filling an array with new Athlete objects, yet I cannot access a specific property of an object in the array.
I am new to working with objects so I'd appreciate any advice on how to make this work. I have added a last line of code to display my input array.
var input = new Array();
var girl=[1,1,1,1];
var boy = [1,1,1,1];
var balleyscore = [100,400,320,50];
var boyHeight = [72,68,65,75];
var girlHeight=[60,57,65,55];
var boyAge = [19,32,22,25];
var girlAge = [20,15,32,18];
//the above are all generate from user inputs
// they go into the object constructor below
function athlete(girl, boy,balleyscore, height, age){
this.girl=girl;
this.boy=boy;
this.balleyscore=balleyscore;
this.height=height;
this.age = age;
};
function insertToObjectArray()
{
var j=0;
var i=0; //insert all our data into one array of the load object
for(j = 0; j < girl.length;j++)
{
input[j]= new athlete(true,false,balleyscore[j],girlHeight[j],girlAge[j]);
}
for(j = girl.length; j <=girl.length+boy.length;j++)
{
input[j]= new athlete(false,true,0,boyHeight[i],boyAge[i]);
i++;
}
};
insertToObjectArray();
document.getElementById("demo").innerHTML=input;
http://jsfiddle.net/qC5j4/1/
To access a property of an object in your array input:
input[0].age
this will allow you to access the first athlete's age
can also be accessed like so:
input[0]['age']
Either way they will both display 20 as the age of the first athlete in the array.
Check it out by console.log(input) in the debugger and then you can play with the data structure.
Ex:
document.getElementById("demo").innerHTML=input[0].age;
Not really sure of your problem, here I have updated your fiddle to display the height property of your athletes by adding the line
output[j]= input[j].height
fiddle
Your athlete object should be for example:
function athlete(age)
{
this.age = age;
}
var item = new athlete(10);
item.age;//10
You can show the height and age like this:
var output = "";
for(var i = 0, length = input.length; i !== length; i++) {
output += "height: "+input[i].height + ", age: " + input[i].age + "<br />";
}
document.getElementById("demo").innerHTML=output;
And there is a little mistake. Use
j < girl.length+boy.length
instead of
j <=girl.length+boy.length
You can access your objects by array index and property name. Change this line document.getElementById("demo").innerHTML=input to this code (list all objects sex and balleyscore in ul#demo):
for (var i=0; i<input.length; i++) {
var node = document.createElement('li'),
txt = document.createTextNode(
(input[i].girl? 'girl' : 'boy') + ' ' + input[i].balleyscore);
node.appendChild(txt);
document.getElementById("demo").appendChild(node);
}
html:
<p><ul id="demo"></ul></p>
FIDDLE
Browser console is very useful for debugging purposes. Try to add this line after objects creation and inspect your array in console:
insertToObjectArray();
console.log(input); // output input array to console

How to iterate over JSON data

The following is my JSON data in a div:
[{"Identifier":"1","Label":"10 Day","Categories":"Standard","UpdatedBy":"Lno","UpdatedAt":"01-02-2013","RefId":"0","ComType":"1","Cs":["944"],"AM":"Error Message","Message":"asdfasdf","Combiner":[{"uniqueID":"1","type":"7","rule":""}]}]
I am accessing it through a JS object:
var myArrayVar=JSON.parse(document.getElementById("populateDT").innerHTML);
I want to iterate over this JS object. The following is my code, but it doesn't access my key/value fields:
for(var i=0; i<=myArrayVar.length;i++){
for(var j=0; j<=myArrayVar.Combiner.length; j++){
var sessionUniqueId= myArrayVar.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=myArrayVar.Combiner[j].type;
alert(sessionType);
var sessionRule=myArrayVar.Combiner[j].rule;
alert(sessionRule);
}
}
Can anyone suggest a solution?
for (var i = 0; i < myArrayVar.length; i++) {
for (var j = 0; j < myArrayVar[i].Combiner.length; j++) {
var sessionUniqueId = myArrayVar[i].Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType = myArrayVar[i].Combiner[j].type;
alert(sessionType);
var sessionRule = myArrayVar[i].Combiner[j].rule;
alert(sessionRule);
}
}
You never use i. You need it to access the current array element, for example:
for(var j=0; j<=myArrayVar[i].Combiner.length; j++){
myArrayVar is your array, myArrayVar[i] is the i-th element in that array and myArrayVar[i].Combiner is the combiner (array) property of the i-th element.
You'll make it yourself a lot easier if you give the current element a name as well. (You probably want to come up with a less generic name such as current though.)
for(var i=0; i<myArrayVar.length;i++){
var current=myArrayVar[i];
for(var j=0; j<current.Combiner.length; j++){
var sessionUniqueId=current.Combiner[j].uniqueID;
alert(sessionUniqueId);
var sessionType=current.Combiner[j].type;
alert(sessionType);
var sessionRule=current.Combiner[j].rule;
alert(sessionRule);
}
}
Also, i cannot equal myArrayVar.length as that index is already out of bounds. Your loop condition should have < instead of <=.
You have an array with one element. That element is in myArrayVar[0] and it is an object. To iterate over the object use a for ... in loop.
var myObj = myArrayVar[0];
for(var key in myObj){
var value = myObj[key];
console.log(key, value);
}
You should also use console.log for debugging. It will show you more information about objects than alert can.
Try using "<" instead of "<=" in the for loops, and "myArrayVar[i].Combiner" instead of "myArrayVar.Combiner".
There are a couple of problems I see. First, your i and j variables go one spot too far. They should be using < instead of <=.
Secondly, you're declaring variables inside the loop. That's fine, but JavaScript isn't block scoped, so you really end up with the same three variables overwriting each other as many times as there are items in the list. Your example data only has one item so you probably won't notice the overwriting problem just yet–but once you have multiple items in the list it could be a problem.

Accessing Array values dynamically

I have Array in this format.
rowData[0] = addRow(aa);
rowData[1] = addRow(aaa);
rowData[2] = addRow(aa);
rowData[3] = addRow(aa);
addRow is a function which gets this value process.But i don't want to give the Array Index, instead i want to give rowData[i], then put in a loop and access the elements.
rowData holds the an object which addRow returns.
var data = [rowData];
var table = Ti.UI.createTableView({
data:data
});
Use the Array.push function to store the data:
rowData.push(addRow(aa));
rowData.push(addRow(aaa));
.
.
.
.
.
Another alternative is:
rowData[rowData.length] = addRow(aa);
rowData[rowData.length] = addRow(aaa);
.
.
.
.
.
Use the regular index based iterations to get the data:
for(var i=0; i< rowData.length; i++){
var curItem = rowData[i];
}
for (var i = 0; i < rowData.length; i++)
{
rowData[i] = addRow(aa);
}
did u mean this?
var rowData = {};
rowData[aa] = addRow(aa);
rowData[aaa] = addRow(aaa);
for loop access
for(var index in rowData){
var data = rowData[index]
...
}
A loop may not be feasible in your case. This may be an idea: you can rewrite the Array.push prototype method:
Array.prototype._push = Array.prototype.push;
Array.prototype.push = function(val){ this._push(val); return this;};
After which you can chain the push operations:
rowData.push(addRow(aa))
.push(addRow(aaa))
.push(addRow(aa))
.push(addRow(aa));
But actually, it looks like you are mixing arrays with objects. Here's an answer I formulated earlier on that subject.

Categories