Push variable from loop into array that is indexed - javascript

I've looked around for awhile and haven't found any solutions. What I'm trying to do is store the variable that contains my option values into an array with an index for each element that is in the variable so I can call it's index.
Here is my code:
var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');
for(i = 0; i < selectArray.length; i++) {
let arrayList = selectArray[i];
let arrayOption = document.createElement('option');
selectField.appendChild(arrayOption);
arrayOption.value = arrayList; // Value Option in Option
arrayOption.innerHTML = arrayList; // Text in Option
let newArray = [];
newArray.push(arrayOption.value);
// This doesn't work I want each element in the variable to be indexed in the array. so I can do for example newArray[0] which will return Package 1 from the value.
}
<select name="fromList" id="testS"></select>
Reason I'm trying to push the option values from my loop variable into the array is because I want to select each of there index and append to them another array that contains data.

You just need to change where you are declaring the newArray. let creates block level scope, so if you delcare it within a loop, it is scoped to just that one iteration of the loop. You don't want the variable re-declared upon each iteration of the loop because that wipes out the earlier value.
var selectArray = ['Package 1', 'Package 2'];
var selectField = document.getElementById('testS');
// You need to declare variables in the scope that you will want to use them
let newArray = [];
for(i = 0; i < selectArray.length; i++) {
let arrayList = selectArray[i];
let arrayOption = document.createElement('option');
selectField.appendChild(arrayOption);
arrayOption.value = arrayList; // Value Option in Option
arrayOption.innerHTML = arrayList; // Text in Option
newArray.push(arrayOption.value);
}
console.log(newArray);
<select name="fromList" id="testS"></select>
Now, the next question is why do you really need to even do this? The option elements in the select can always be gotten on-demand as an array with this:
var options = Array.prototype.slice.call(document.querySelectorAll("#testS > option"));

Related

access variable from outside loop

I know that this is fundamental JS, but I'd like a simple explanation. From what I've read, If i declare an empty variable outside of my loop, the variable inside the loop should be accessible globally? Or am I totally wrong?
I would like to access randAd from outside my for loop.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd;
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd = (mobileAds[randNum]);
}
If you want to access every element of randAd outside the for loop try like this var randAd = []; to initialize it as an array. You can easily access it after your for loop but If you use it as a simple variable var randAd;then you'll get the last variable always (it overwrites). So initialize it as an array and push every element inside loop before outputting it.
var mobileAds = [
"mobile/bb.jpg",
"mobile/eyeko.jpg",
"mobile/farfetch.jpg",
"mobile/fsb.jpg"
];
var randNum = (Math.floor(Math.random() * mobileAds.length));
var randAd = []; // see the change here
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]); // push every element here
}
console.log(randAd);
You are overthinking. You have done the hard bit in getting a random number between 0 and array's length. So, just get the ad at that index:
var randAd = mobileAds[randNum];
No need to use for loop at all.
If you would like to use randAd it should be initialised as an empty array [] and then push in that array from inside your loop randAd.push(). Like this:
var randAd=[];
var i;
for (i = 0; i < mobileAds.length; ++i) {
randAd.push(mobileAds[randNum]);
}

For loop looping one too many times

I have some code:
var cart = [];
var items = [];
var cart_node = document.querySelectorAll('#tblItineraryModuleStayDetail > tbody > tr');
var cart_as_array = Array.prototype.slice.call(cart_node, 2); // start at item 3 (2)
for(var i=0;i<cart_as_array.length;i+=2) {
items.push(cart_as_array[i]);
}
Now, in the console if I type items I get:
So I expect the loop to go around once in this instance.
Here's my loop:
for(i=0; i < items.length; i++) {
// set vars
cart[i] = {};
var name = items[i].querySelector('.txtStayRoomDescription').textContent;
var price = items[i].querySelector('.tblItinPriceSummary tr td:last-child').textContent;
var brand = items[i].querySelector('.txtStayRoomLocation').textContent;
// add to object
cart[i].name = name;
cart[i].price = price;
cart[i].brand = brand;
// add to cart array
cart.push(cart[i]);
}
Which gives:
I expected a result with array cart containing one item object not two. But it has two identical objects.
What's going on here?
You're first setting the ith element of the cart array as your object, then also pushing it onto the end; this will put two copies in, as you see.
Edit for question in comments:
Let's go through your code line by line:
for(i=0; i < items.length; i++) {
// set vars
cart[i] = {};
After cart[i] = {} puts an empty object in the cart array at index i; if there was something there before, it will be overwritten, otherwise the array will simply be added.
// stuff setting properties removed
// add to object
cart[i].name = name;
cart[i].price = price;
cart[i].brand = brand;
Now, the object at cart[i] has received the attributes you constructed. The cart array now contains an object with these name, price, and brand attributes at position i.
// add to cart array
cart.push(cart[i]);
Now, in addition to the reference at i, you've pushed a second reference to the object stored at i on to the end of the array. This will produce the behavior you are observing: the object will be in the array twice.
I would recommend changing cart[i] = {} (and the associated code that adds properties of this object) to construct the object while it is stored in a local variable, then push it on to the array at the end of the loop.
At line 3 of your code you create an empty object in your array:
cart[i] = {};
then at line 14 you push that object into your array again:
cart.push(cart[i]);
You should instead just create an object, and push it at the end:
var item = {};
// ... add properties to item ...
cart.push(item)

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.

Loop Variable in Jquery

I'm using for() to loop a function. In this function, you need to have different variable to specific which container will be update.
When loop, the variable will use string+count integer to have different var name. Example: t=1 > var title1, t=2 > var title2 etc.
Example code:-
for(t = 1; t <= 5; t++) {
var title(t) = function(e){}
}
If I use var var title+t = function(e){}, its not working.
Hope any one can help me on this.
Arrays let you store multiple values and refer to them by an index number. For example:
var title=[];
for (var t=0; t<=4; t++) {
title[t] = //something
}
You can then use an index like title[2] to access items in the array. Arrays in Javascript start counting at 0, so the first item is title[0].

How can I add additional elements to my array?

I was trying to get the country name and put it in the temparray, so that I can use the temparray to check the country (line 14). The problem is temparray can only contain one value and upon increasing the array length size by using temparray.length = 4, the heat map won't show up in the page.
The code below is to check duplicate name entry from within the array. If the country name is repeated, it will add the past value and its current value and add it into the data table again as the old row.
var i;
var suq = 0;
var temparray = [""];
var rowcount= 0;
//set the value
for (i = 0; i<count; i++){
var countryname = countryarray[i];
var hostcount = hosthitcount[i];
//document.write("hello");
for (rowcount=0;rowcount<temparray.length;rowcount++){
//check for any repeated country name
if (temparray[rowcount] != countryname){
data.setValue(suq, 0, countryname);
data.setValue(suq, 1, hostcount);
temparray[rowcount] = countryname;
//document.write("win");document.write("<br/>");
suq++;
}else{
//get the hits //rowindex
var pastvalue = data.getValue(rowcount,1);
//add the previous value with current value
var value = parseInt(hostcount)+parseInt(pastvalue);
value+= "";
//document.write(value);
//put it in the table
data.setValue(rowcount,1,value);
// document.write("lose");document.write("<br/>");
}
}
}
I don't really understand what you are trying to do with temparray. It can surely contain more than one element with a temparray.push(countryname). Maybe this JavaScript array reference will help you?

Categories