最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - access variable from outside loop - Stack Overflow

programmeradmin7浏览0评论

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

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]);
}
Share Improve this question asked Nov 18, 2017 at 14:38 Scott BrownScott Brown 3341 gold badge2 silver badges13 bronze badges 2
  • Duh. Thanks @adiga – Scott Brown Commented Nov 18, 2017 at 14:53
  • The answer you have marked as accepted creates an array with the same ad repeated 4 times. Did you intend to create an array or a single string variable in randAd? – adiga Commented Nov 18, 2017 at 15:54
Add a ment  | 

3 Answers 3

Reset to default 8

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]);
}
发布评论

评论列表(0)

  1. 暂无评论