Error with declaring variables in for loop - javascript

I just want set 2 arrays which should contain for loop output.
Here's code:
var key_ls = new Array();
var value_ls = new Array();
for (var a in window.localStorage) {
key_ls[a] = a;
value_ls[a] = localStorage[a];
}
and it gives me no result. What do i wrong?

What you're looking for is key_ls.push(a), which will simply add another item to the array. Also use [] instead of new Array().

Related

cannot iterate through array and change value in JS

I have to iterate through an array, change one of its values, and create another array refelecting the changes.
this is what I have so far:
JS:
var arr = new Array();
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
arr['t2'] = i;
last.push(arr);
}
console.log(last);
Unfortunately, these are my results
As you can see, I am not getting the results needed as 0,1,2.. instead I am getting 2, 2, 2..
This is what i would like my results to be:
How can I fix this?
You have to make a copy, otherwise you are dealing with reference to the same object all the time. As it was said before - javascript does not have associate arrays, only objects with properties.
var arr = {}; // empty object
arr['t1'] = "sdfsdf";
arr['t2'] = "sdfsdf";
arr['t3'] = "sdfsdf";
arr['t4'] = "sdfsdf";
arr['t5'] = "sdfsdf";
var last = new Array();
for (var i = 0; i <= 5; i++) {
var copy = JSON.parse(JSON.stringify(arr)); //create a copy, one of the ways
copy['t2'] = i; // set value of its element
last.push(copy); // push copy into last
}
console.log(last);
ps: you can use dot notation arr.t1 instead of arr['t1']
The array access with ['t2'] is not the problem. This is a regular JavaScript feature.
The problem is: You are adding the SAME array to "last" (5 times in code, 3 times in the screenshot).
Every time you set ['t2'] = i, you will change the values in "last" also, because they are actually just references to the same array-instance.
You must create a copy/clone of the array before you add it to "last".
This is what will happen in all languages where arrays are references to objects (Java, C#...). It would work with C++ STL though.

Is this a valid array (value)?

var leaguetable = new Array();
leaguetable[0]= #leaguetable;
leaguetable[1]= #leaguetable1;
leaguetable[2]= #leaguetable2;
leaguetable[3]= #leaguetable3;
leaguetable[4]= #leaguetable4;
leaguetable[5]= #leaguetable5;
leaguetable[6]= #leaguetable6;
leaguetable[7]= #leaguetable7;
leaguetable[8]= #leaguetable8;
Can you have ID as the array values like I have done? Because this is not working for me at the moment.
You need to wrap your values inside quotes '#leaguetable1', '#leaguetable2'.....
However, you can just use a simple for loop to achieve it automatically instead of manually adding it:
var leaguetable = new Array();
leaguetable[0]= '#leaguetable';
for(var i=1; i<=8; i++) {
leaguetable[i] = '#leaguetable' + i;
}
console.log(leaguetable);
Fiddle Demo
Bo, #foo is not a valid JavaScript expression. You meant '#foo' instead.
Also, you can (should) use an array literal instead of new Array:
var leaguetable = [
'#leaguetable',
'#leaguetable7',
...
'#leaguetable8'
];

very simple, javascript arrays syntax

I have a very simple JS Arrays question, my simple canvas game has been behaving differently when I replaced one block of code with another. Could you look them over and see why they are functionally different from one another, and maybe provide a suggestion? I may need these arrays to have 20+ items so I'm looking for a more condensed style.
There's this one, which is short enough for me to work with, but doesn't run well:
var srd=new Array(1,1,1);
var sw=new Array(0,0,0);
var sang=new Array(0,0,0);
var sHealth=new Array(20,20,20);
And then there's the original one, which is longer but works fine:
var srd = new Array();
srd[1] = 1;
srd[2] = 1;
srd[3] = 1;
var sw = new Array();
sw[1] =0;
sw[2] =0;
sw[3] =0;
var sang = new Array();
sang[1] = 0;
sang[2] = 0;
sang[3] = 0;
var sHealth = new Array();
sHealth[1] = 20;
sHealth[2] = 20;
sHealth[3] = 20;
Arrays are zero-indexed in JavaScript. The first element is 0, not 1:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
Also, you may want to use the more common array constructor:
var srd = [1, 1, 1];
I have a feeling that you may be assuming that the first element is 1 instead of 0, which is why the first version doesn't work while the second one does.
You should do this....in Arrays values are stored as such that first one is at 0 and so on.
so 1st value will be accessed as this...
var x = abc[0]; //first value of array abc being assigned to x.
Do this (you see i actually read your question and this is what you like)
var srd=['',1,1,1];
var sw=['',0,0,0];
var sang=['',0,0,0];
var sHealth=['',20,20,20];
you can declare an array(object) in javascript like this
var x = []; -------------Literal - its a shortcut provided by JS to quickly declare something as an Array.
var x = new Array; --Array constructor
Things to look up regarding
literal
object literal
proto
word new
function object
function property prototype
You can also do these:
var x=1,y=2,
z=3,
f;
var b = something || {}; \\become a copy of object called something if it's not there then become an empty object.
It looks like one starts the arrays at index 0 and the other one starts at index 1
It depends on your implementation, but it's likely because of arrays being 0-indexed. In your first block of code, each number is offset by one index spot from the second block. The first one is equivalent to:
var srd = new Array();
srd[0] = 1;
srd[1] = 1;
srd[2] = 1;
in the way you wrote it for the second block.

Convert string to become variable

I have multiple variables containing JSON as string (received from AJAX).
data.output_data_1234
data.output_data_5678
I convert them to Array:
var outputdataarr = new Array(data.output_data_1234);
This works fine, but how do I add a number to the var name:
var outputdataarr = new Array('data.output_data_'+formid+'');
this one does not work.
formid contains a proper number.
This does not work too:
var outputvar = window['data.output_data_' + formid];
var outputdataarr = new Array(outputvar);
Please help. Thanks.
You probably mean, you need something like this:
var outputdataarr = new Array(data['output_data_'+formid]);
You can only use string in square brackets as an object field identifier. It cannot contain '.'.
UPDATE:
However, you will probably need a loop to fill the whole array, e.g.
var outputdataarr = new Array();
for (var i=1000; i<2000; i++) {
outputdataarr.push(data['output_data_'+formid]);
}
Use [] instead of new Array is better.
var outputdataarr = [];
outputdataarr.push(data['output_data_'+formid]);
//and so on

creating and parsing a 3D array in javascript? [duplicate]

This question already has answers here:
Is it possible to create an empty multidimensional array in javascript/jquery?
(8 answers)
Closed 9 years ago.
can any one help me to create and parse a 3d array in javascript.
im having a questionId each question Id have a selected option and an optional option text.
so i need to create a 3d array for questionId,optionId,optionText(string)..
Thnks in advance
A one dimension array would be:
var myArr = new Array();
myArr[0] = "Hi";
myArr[1] = "there";
myArr[2] = "dude";
alert(myArr[1]); // Alerts 'there'
A two dimensional array would be:
var myArr = new Array();
myArr[0] = new Array("Val", "Va");
myArr[1] = new Array("Val", "yo");
myArr[2] = new Array("Val", "Val");
alert(myArr[1][1]); // Alerts 'yo'
A 3D array is more complicated, and you should evaluate your proposed use of it as it has a limited scope within the web. 99% of problems can be solved with 1D or 2D arrays. But a 3D array would be:
var myArr = new Array();
myArr[0] = new Array();
myArr[0][0] = new Array()
myArr[0][0][0] = "Howdy";
myArr[0][0][1] = "pardner";
alert(myArr[0][0][1]); // Alerts 'pardner'
var data = new Array();
data starts off as a regular one-dimensional array. A two dimensional array is really just an array of arrays. So you could do something like
for (var i = 0; i<numberOfQuestions; i++){
data[i] = new Array();
data[i][0] = something;
data[i][1] = somethingElse;
}
Alternatively you could use the following approach
for (var i = 0; i<numberOfQuestions; i++){
data.push([something, somethingElse]);
}
In any case, at some point you are going to need a loop to populate your initial array with sub-arrays to get the 2d effect.
Okay, so as I said in comment to the question, I think you actually need 2D array. That is, if you have N number of questionIds and each questionId has two properties: optionId and optionText
You can create it somehow like this:
var twoD = new Array();
twoD[1] = new Array();
twoD[1]['optionId'] = 3;
twoD[1]['optionText'] = 'blabla';
twoD[2] = new Array();
twoD[2]['optionId'] = 5;
twoD[2]['optionText'] = null;
alert(twoD[1]['optionId']);
Although note that array with associative key is actually an object in JavaScript.
Update: looping through JavaScript
for(var question : twoD){
alert(question['optionId']);
alert(question['optionText']);
}
hi you can create the nth dimension error in javascript one of the example is below
var apple = new Array();
apple[1] = new Array();
apple[1][1] = new Array();
apple[1][1][1] = 'yourname'
now you can use the recursive function to iterate through the array and check and pare every thing.

Categories