Looping the creation of multiple variables - javascript

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);

Related

How to add diferent text for each element in DOM

Can someone tell me what is wrong with this code. I want to add a number from 0 to 4, but it added only the last number from my loop.
Thank you very much in advance.
<script>
for (i = 0; i < 5; i++) {
var createEl = i;
var createEl = document.createElement("li");
for (j = 0; j < 5; j++) {
createEl.innerHTML = [j];
}
console.log(createEl);
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
//<li>4</li>
}
You dont need the nested for loop just use the i value from the first loop
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
console.log(createEl);
}
This will only print the tags to console. In case you want to put them in another tag use it like this:
var node = document.createElement("div");
for (i = 0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
node.appendChild(createEl);
}
You don't need two loops for that.
var ulContainer = document.createElement("ul");
for (i=0; i < 5; i++) {
var createEl = document.createElement("li");
createEl.innerHTML = i;
ulContainer.appendChild(createEl);
}

Creating a function to create multiple arrays with the same properties

I want to create multiple arrays that contain the same basic layout. Currently, i have
Array(10); //base array with moving blocks
for(var i = 0; i < 10; i++){ //creating an array within an array (2d)
base[i] = new Array(22);
}
var background = new Array(10); //background array with stationary blocks
for(var z = 0; z < 10; z++){ //same as before
background[z] = new Array(22);
}
var nextBlock = new Array(10); //next block array
for(var i = 0; i <10; i++){
nextBlock[i] = new Array(22);
}
and would like to have something similar to:
function arrayCreator(rows,cols){
var array = newArray(rows);
for(var i = 0;i < rows;i++){
array[i] = newArray(cols);
}
}
var base = arrayCreator(10,22);
var background = arrayCreator(10,22);
var nextBlock = arrayCreator(10,22);
but cant get it working. How should I approach this?
Looks like you forgot the return statement.
function arrayCreator(rows,cols){
var array = newArray(rows);
for(var i = 0;i < rows;i++){
array[i] = newArray(cols);
}
return array;
}

initialize variable repeatedly using for loop in javascript

my question is can i possibly initialize variables repeatedly (with changing only numbers after them) this is my code
for(i = truStorage.getItem('elementCount'); i>0; i--) {
var obj = truStorage.getItem("element_" + i);
var [obj_+i] = element(erd.Entity , obj.posx, obj.posy, obj.text );}
};
basically i just want to initialize a variable like
something_i = "";
and the result will be like this
var element_1 = element(erd.Entity, 100, 200, "Employee");
var element_2 = element(erd.Entity, 100, 400, "Salesman");
var element_3 = element(erd.WeakEntity, 530, 200, "Wage");
var element_4 = element(erd.IdentifyingRelationship, 350, 190, "gets paid");
im not trying to use variables as a storage but rather to instantiate an element for a function.
This is a job for an array.
var something = [];
var somethings = 5;
for(var i = 0; i < somethings; i++) {
something[i] = "";
}
You should now be able to access the five values like this:
console.log(something[0])
console.log(something[1])
console.log(something[2])
console.log(something[3])
console.log(something[4])
Notice you use 0 to access the first element. That's just how it is because JavaScript arrays are zero-based.
This is best scenario to use array:
var counter=0,something = new Array();
for(i = truStorage.getItem('elementCount'); i>0; i--) {
something[counter] = truStorage.getItem("element_" + i).text;
counter++;
}
};
Try:
for(var i=1; i<=4; i++) {
this["something_" + i] = i;
}
console.log(something_1); //outputs 1;
console.log(something_2); //outputs 2;
console.log(something_3); //outputs 3;
console.log(something_4); //outputs 4;
Note: using an array will be faster!

Create arrays dynamically in a loop with javascript

Here's a pseudocode example about what I'm trying to do:
var totalLanguages = XX;
for(var i = 0; i < totalLanguages; i++){
var dynamicArray + i = new Array();
/*.....*/
}
I need to create dynamically many arrays as the value of totalLanguages which can be either number.
This is to be able to do something like this:
for(var i = 0; i < totalLanguages; i++){
var arrayLanguages["es"] = dynamicArray+i;
var arrayLanguages["en"] = dynamicArray+i;
}
Is there any way to do this?
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
languages[languageNames[i]] = [];
}
You are basically trying to recreate an array with variable names. Just use an Array to start out!
var dynamicArray = [];
for(var i = 0; i < totalLanguages; i++) {
dynamicArray[i] = new Array();
}
You can use multi-dimensional arrays:
var languagesArray = new Array(totalLanguages);
for(var i = 0; i < totalLanguages; i++) {
var innerArray = new Array();
innerArray.push("Hello");
innerArray.push("World");
languagesArray[i] = innerArray;
}
console.log(languagesArray[0][0]);
See: How can I create a two dimensional array in JavaScript?
How about:
for(var i = 0; i < totalLanguages; i++){
window["dynamicvariable " + i] = new Array();
/*.....*/
}

Remove <param> node from <object> and replace it with new <param> values

How can I add tag to Object , replacing its original tag with modified values. I am using the JavaScript to perform this replacement.
But the param is not getting replaced or removed.
how to identify a particular param under
Can any one suggest please.
Thank you!
function autoObjectFun() {
var objects = document.getElementsByTagName('object');
var len1 = objects.length;
for(var j = 0; j < len1; j++) {
var paramObj = objects[j].getElementsByTagName('param');
var len = paramObj.length;
for(var i = 0; i < len; i++) { var srcStr = paramObj[i].getAttribute('name'); if (srcStr == 'flashvars' ) { var newParamObj = document.createElement('param'); newParamObj = paramObj[i].cloneNode(true); var params = paramObj[i].getAttribute('value'); var newparams = ''; var paramplay = 'autoplay=0&'; newParamObj.setAttribute('value', paramplay);
paramObj[i].removeNode(true);
var newObject = objects[j].cloneNode(true);
var parent1 = objects[j].parentNode;
newObject.appendChild(newParamObj);
parent1.replaceChild(newObject,objects[j]); }
}}}
There is no native method removeNode(), this will cause an error and stop the further execution of your statements.
Try:
paramObj[i].parentNode.removeChild(paramObj[i]);
..instead.

Categories

Resources