access variable from outside loop - javascript

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

Related

create objects for loop and pushing them into an array js

I wish to create an array called allEnemies, which contains "bugs" which belong to a Class "Enemy". I'm trying to do it in a for loop because later on the var "bug" will be modified. The problem is that the objects created "if I'm creating them" don't get into the array "allEnmies". Thank you in advance.
var allEnemies = [];
var random_speed = function() {
return Math.floor(Math.random() * (300 - 80)) + 80;
};
var random_y = function() {
var postions = [60, 143, 226];
return positions[Math.floor(Math.random() * 3)];
};
var create_enemies = function() {
var bugs = 4;
for (var i = 0; i < bugs; i++) {
var bug = new Enemy();
bug.speed = random_speed();
bug.y = random_y();
bug.x = 0;
allEnemies.push(bug);
}
};
Demo - http://jsfiddle.net/ubkusb6r/
Ok, so a few things:
1) Since you've declared the for loop using an anonymous function assigned to a variable you need to invoke the function via that variable create_enemies(). Without this, your code won't run.
2) You need to create an Ememy constructor (if you haven't done so yet).
3) You misspell positions at one place in your code...leading to an error.
Take a look at the JSFiddle and let me know if it answers your question (the fiddle includes console.log statements to track the array).

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

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].

A good way to associate a counter to each member of an array in Javascript?

I have an array of strings in Javascript like `var elements = ["string1", "string2"]; The array is created dynamically so it could contain any number of strings. I want to associate a counter to each element of the array. The counter will increment or decrement during the webpage's life.
I was going to try element["string1"].counter = 1; but it didn't work.
What's a good way to implement this?
If you had an array var elements = ["string1", "string2"], you could not access an element with elements["string1"], you are using the value not the index. elements[0] is the correct form of access to the element, using the numerical key.
Even then, strings are special types of object and do not appear to take additional parameters readily, at least not when I tested a moment ago. Which is odd.
You could quickly knock the array in to a set of objects with separate text and counter components.
var elements = ["string1", "string2"];
var elementsWithCounter = [];
for(var index = 0; index < elements.length; index++) {
elementsWithCounter[i] = { text: elements[index], counter: 1 };
}
You could also create a "hash table" using a plain object such as:
var counter = {};
for(var i = elements.length; i--; ) {
counter[elements[i]] = 1;
}
Then you could increment the counter with:
counter['string1'] += 1;
or
counter[elements[0]] += 1;
This might help you.
elementArray = ["string1", "string2"]
function setCounter(str, val) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) elementArray[i].counter = val;
}
}
function getCounter(str) {
for (var i = 0; i < elementArray.length; i++) {
if (str === elementArray[i]) return elementArray[i].counter;
}
}
setCounter("string1", 5);
getCounter("string1");
Alternatively just access elementArray[index].counter
Javascript primitives/built in objects can't have properties/attributes added to their prototype (i.e. String.prototype.counter = -1 doesn't work correctly). Image, String, Date, Array all can't have properties added.
Maybe instead of a string you should make it an object, similar to what Orbling has posted.

Categories