Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]);
}
like image 961
Scott Brown Avatar asked Nov 18 '17 14:11

Scott Brown


2 Answers

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);
like image 106
Always Sunny Avatar answered Oct 10 '22 23:10

Always Sunny


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.

like image 36
adiga Avatar answered Oct 11 '22 00:10

adiga