Global vars with jsFiddle

二次信任 提交于 2019-12-24 04:35:09

问题


In the jsFiddle environment, I wish to create a loop that displays numbers 1 thru 10 in random order, with no repeats.

jsFiddle here

Among other things, having difficulty with global variables in the jsFiddle environment.

Would appreciate:

  1. Explanation re global vars in jsFiddle
  2. Making my code work (desired goal: print numbers 1 to 10 in random order, via loop)

Thank you

For posterity, here is the code from the jsFiddle:

HTML:

<div id="response"></div>
<input type="button" id="mybutt" value="Get Next" />

javascript/jQuery:

var cnt;
var window.arrDone = [];

function nextQues() {
    return Math.floor(Math.random()*3) + 2;
}

$('#mybutt').click(function() {
    cnt++;
    console.log('Count is now: ' + cnt);
    if (cnt < 10) {
        nn = nextQues();
        console.log('Testing: ' + nn);
        if (window.arrDone.indexOf(nn) > -1) {
            console.log('Already Seen: ' + nn);
        }else{
            console.log('FOUND NEW: ' + nn);
            window.arrDone.push(nn);
        }
        $('#mybutt').trigger('click');
    }
});

For Posterity:

Anyone stumbling across this question while researching their own solution should also check out this, related, SO post:

Is javascript namespace polluted?

  • Ensure you read the answer by Joe Enos, and comment discussion underneath

回答1:


Try this:

var cnt = 0;
var window = {};
window.arrDone = [];

Demo here

Globals in jsfiddle are the same as in websites. Although the best is to use no wrap in jsfiddle's top-left menu, and have your own .ready() function. Otherwise it will wrap your code in a onload function that you don't have on your site.



来源:https://stackoverflow.com/questions/18835396/global-vars-with-jsfiddle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!