问题
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:
- Explanation re global vars in jsFiddle
- 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