Creating static variables is not an option in this case becouse it would take to long time and ineffective to what im trying to accomplish. I have an Array with images and I'm trying to create a way to make divs according to the length of the array. 1,2,3,4 etc.
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
Which will result in an array length of 3. I would like to create 3 variables for this.
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
This seems not to be working for some reason. I tried to create a div array/list outside the for loop aswell.
var div = [];
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
Still not working. I dunno why this is not working. Javascript only
EDIT: (not working) i mean it gives me syntax error.
You have defined div already. In loop you shouldn't be saying like var div again.
BTW var div[ will cause a syntax error.
Use this
div[i] = document.createElement('div');
instead of
var div[i] = document.createElement('div');
Any way I'll prefer saying this at that place
div.push(document.createElement('div'));
And this will cause i > totalimages an infinitive loop, say i < totalimages instead.
i < totalimages
not
i > totalimages
Make sure you don't use var inside the array if you're assigning new values:
var div = [];
for (var i = 0; i < totalimages; i++){
div[i] = document.createElement('div');
}
DEMO
In short:
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
var div = [];
for (var i = 0; i < totalimages; i++){
div.push(document.createElement('div'));
}
Related
I want to loop the creation of various variables as to cut down on lines of code. If I need to create 10 variables like so:
var par01 = document.createElement("p");
var par02 = document.createElement("p");
var par03 = document.createElement("p");
var par04 = document.createElement("p");
var par05 = document.createElement("p");
var par06 = document.createElement("p");
var par07 = document.createElement("p");
var par08 = document.createElement("p");
var par09 = document.createElement("p");
var par10 = document.createElement("p");
...using a basic For Loop. I seem to be having some issues in setting it up:
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
var par[loopCounter] = document.createElement("p"); }
Create an array before the loop, then fill it with new entries inside the loop. You want dynamic declaration otherwise, that is a classical problem afaik.
var arr = [];
for (var i = 0; i < 11; i++) {
arr.push( document.createElement("p") );
}
You're almost there, just declare your array before the loop. You can either assign to each array item using the counter like you did, or probably easier to just use push():
var par = [];
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
par.push(document.createElement("p"));
}
console.log(par.length);
You better use an array instead of doing this kind of stuff.
var pCollection =Array();
for (var loopCounter = 1; loopCounter < 11; loopCounter++) {
pCollection.push(document.createElement("p"));
}
Now to access your elements just iterate over the array;
for (var loopCounter = 1; loopCounter < pCollection.length; loopCounter++) {
var pElement = pCollection[loopCounter] ;
}
You must define the array before, better (in performance terms) if you know the length previously.
var loopCounter,
par[] = new Array(11);
for (loopCounter = 0; loopCounter < array.length; loopCounter++) {
par[loopCounter] = document.createElement("p");
}
If the length is dynamic, you can initialize empty, and add elements using push() function.
Use an array and push each object into it:
var pCollection = [];
for (var loopCounter = 0; loopCounter < 10; loopCounter++) {
pCollection.push(document.createElement("p"));
}
console.log(pCollection);
Bit of a theoretical question, if I had a JavaScript application where I have multiple Players and for each player there will be 100 computer generated maths questions.
In single player mode it's easy, just generating the questions for the one player:
var player1Qs = [];
for (i = 0; i < maxQustions; i++) {
// Generate Question Object
var question = {};
...
// Add to Array
player1Qs.push(question);
}
That works with no issue. However, when I add a second player into the mix using the same sort of idea as above is where I get a bit puzzled. I'm tryinng to do it without using a multi-dimensional array becasue I'm trying to keep it as simple as possible, but it might be unavoidable.
So player 2 would look something similar to this:
var player1Qs = [];
var player2Qs = [];
for (i = 0; i < playerCount; i++) {
for (j = 0; j < maxQustions; j++) {
// Generate Question Object
var question = {};
...
// Add to Array
???
}
}
Would there be a way of me adding to those two arrays dynamically using a for loop? Or would I need a containing array of players and inside that an array for the questions?
Something like this should do the trick:
// Make sure all players exist.
var players = [];
for (var i = 0; i < playerCount; i++) {
players.push({ name: "Player " + i, questions: [] });
}
// Create questions
for (var i = 0; i < maxQuestions; i++) {
// Generate Question Object
var question = {};
// Do stuff with this question
// Assign the current question to all players.
for (var j = 0; j < playerCount; j++) {
players[j].questions.push(question);
}
}
I'm tryinng to do it without using a multi-dimensional array becasue I'm trying to keep it as simple as possible
I would argue that having a two-dimentional array is the simplest use-case, as you suggest in your question:
Or would I need a containing array of players and inside that an array
for the questions?
The answer is yes (at least if you want to keep it simple). The players array will keep all the players, and each player can then have 100 questions each.
var maxQustions = 100;
var players= []
var player1Qs = [];
var player2Qs = [];
players.push(player1Qs);
players.push(player2Qs);
for (i = 0; i < players.length; i++) {
for (j = 0; j < maxQustions; j++) {
var question = {};
players[i].push(question);
}
}
follow this approach, I assume you have dynamic players and its array:-
var data = {};
var player = [1,2]
var c = [1,2,3,4,5]
for(j=0;j<player.length;j++)
{
data['players'] = player;
data['questions'] = c
}
console.log(data)
I'm working on Google Script and I'm testing different ways to create two dimensions arrays.
I have created an array like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0][0]="x";
codes[0][1]="x";
codes[0][2]="x";
codes[0][3]="x";
codes[1][0]="x";
codes[1][1]="x";
codes[1][2]="x";
codes[1][3]="x";
codes[2][0]="x";
codes[2][1]="x";
codes[2][2]="x";
codes[2][3]="x";
codes[3][0]="x";
codes[3][1]="x";
codes[3][2]="x";
codes[3][3]="x";
codes[4][0]="x";
codes[4][1]="x";
codes[4][2]="x";
codes[4][3]="x";
codes[5][0]="x";
codes[5][1]="x";
codes[5][2]="x";
codes[5][3]="x";
And it is working fine.
I read following links here, here and here.
But when I do it like this:
var codes = new Array(6);
for (var i = 0; i < 6; i++) {
codes[i] = new Array(4);
}
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
It didn't work, so I tried like this:
var codes = new Array([["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"],["x","x","x","x"]]);
it didn't work either.
When the code don't work, I get no error, just no display of the values.
What am I doing wrong? It looks to be the same code and the two not working ways are recommended in many documentations.
W3schools says that there is no need to use new Array().
For simplicity, readability and execution speed, use literal method ex:
var animals = ["cat", "rabbit"];
Reason why your code was not working is that you're equaling codes inside the loop and after end of loop scope 'codes' is getting only the last set array. Instead you should push those arrays to codes.
var codes = [];
for (var i = 0; i < 6; i++) {
codes.push([i]);
}
console.log(codes)
codes[0]=["x","x","x","x"];
codes[1]=["x","x","x","x"];
codes[2]=["x","x","x","x"];
codes[3]=["x","x","x","x"];
codes[4]=["x","x","x","x"];
codes[5]=["x","x","x","x"];
Better yet, two for loops to create the double array:
var codes = [], // Initiate as array, in Javascript this is actually fastre than using new (I don't know any cases you should use new)
rows = 6,
columns = 6;
for (var i = 0; i < rows; i++){
codes.push([]); // Initiate
for (var j = 0; j < columns; j++){
codes[i][j] = 'x';
}
}
Other idea, pre-initiate an array with the correct columns then copy:
var arrTemp = [],
codes = [],
rows = 6,
columns = 6;
for (var j = 0; j < columns; j++)
arrTemp[i] = 'x';
for (var i = 0; i < rows; i++)
codes.push( arrTemp.slice(0) ); // If you just push the array without slice it will make a reference to it, not copy
Other way to pre-initiate the array with 'x's:
arrTemp = Array.apply(null, Array(columns)).map(function () {return 'x'});
I have the following javascript
information0 = xmlDoc.getElementsByTagName("info")[0].textContent;
information1 = xmlDoc.getElementsByTagName("info")[1].textContent;
information2 = xmlDoc.getElementsByTagName("info")[2].textContent;
information3 = xmlDoc.getElementsByTagName("info")[3].textContent;
information4 = xmlDoc.getElementsByTagName("info")[4].textContent;
information5 = xmlDoc.getElementsByTagName("info")[5].textContent;
information6 = xmlDoc.getElementsByTagName("info")[6].textContent;
I want to create a new var for each index number. There are 600 in total. How can I do this using a for loop?
Thanks in advance
The best thing here is to use an array, not a bunch of individual variables.
var information = [];
var index;
var info = xmlDoc.getElementsByTagName("info");
for (index = 0; index < info.length; ++index) {
information[index] = info[index].textContent;
}
Um... use an array? Also, don't call getElementsByTagName repeatedly, it's expensive!
var tags = xmlDoc.getElementsByTagName('info'), l = tags.length, i, information = [];
for( i=0; i<l; i++) information[i] = tags[i].textContent;
If you're in a reasonably up-to-date browser:
var information = [].map.call(xmlDoc.getElementsByTagName('info'),function(a) {return a.textContent;});
Like this:
var information = [],
i,
elements = xmlDoc.getElementsByTagName("info"),
n = elements.length;
for (i = 0; i < n; ++i) {
information[i] = elements[i].textContent;
}
You need to use an array.
var infoTags = xmlDoc.getElementsByTagName("info"),
i = 0,
len = infoTags.length,
values = []; //array literal syntax, you could also use new Array()
for (; i < len; i++) {
values.push(infoTags[i].textContent); //push the textContent into the array
}
Things that you should note:
I cached the result of getElementsByTagName instead of performing the query multiple times.
I cached the length property of infoTags. That avoids multiple property lookups to access infoTags.length on every iterations. Property lookups are expensive in JavaScript.
To know how you can work with arrays, have a look at the Array object.
-
I am using javascript, using regex to scrape images from html code.
I want the loop to run either until the script finds no more images or until it reaches 12.
I'm trying the following but not working:
var imgs = d.getElementsByTagName('img'), found = [];
for(var i=0,img; ((img = imgs[i]) || ( $i < 13)); i++)
Is this possible? Am I on the right lines?
Quite new to javascript but trying!
You should use && instead of ||. Also, $i should be i.
for(var i=0, img; (img = imgs[i]) && (i < 12); i++)
found.push(img);
Assuming that you want found to contain those first 12:
var imgs = d.getElementsByTagName('img');
var found = [].slice.call(imgs, 0, 12);
You have to use [].slice.call(imgs, ...) instead of imgs.slice() because imgs is only a pseudo-array, and not a real array.
An alternative to writing [].slice is Array.prototype.slice.
If you want to do something else inside the loop, just use the array created above to ensure that you only work on the first 12 images:
for (var i = 0, n = found.length; i < n; ++i) {
// do something with found[i];
}
I personally hate when people do assignment in the condition clause of a for loop, since it looks like someone mistook an assignment (=) for a comparison (=== or ==). Better to do the logic elsewhere.
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length,
max = imgsLength > 13 ? 13 : imgsLength;
for (i = 0; i < max; i++) {
found.push(imgs[i]);
}
or
var imgs = d.getElementsByTagName('img'),
found = [],
i,
imgsLength = imgs.length;
for (i = 0; i < 13 && i < imgsLength; i++) {
found.push(imgs[i]);
}
For Loop with multiple statements
let products= [...]
let users= [...]
for(let i=0,userParam = null, productParam=null; i<products.length; i++, userParam=products[i], productParam=products[i]){
....
}