全球变量与jsFiddle [英] Global vars with jsFiddle

查看:70
本文介绍了全球变量与jsFiddle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jsFiddle环境中,我希望创建一个循环,以随机顺序显示数字1到10,没有重复。

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

jsFiddle here

jsFiddle here

除此之外,在jsFiddle环境中遇到全局变量有困难。

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

不胜感激:


  1. 解释jsFiddle中的全局变量

  2. 让我的代码工作(所需目标:以随机顺序打印数字1到10,通过循环)

谢谢

对于后代,这里是来自jsFiddle的代码:

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






对于后人:

任何在研究自己的解决方案时遇到这个问题的人都应该查看这个相关的SO帖子:

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

javascript命名空间是否被污染?


  • 确保您阅读Joe Enos的答案,并在下面评论讨论

推荐答案

试试这个:

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

演示这里

Demo here

jsfiddle中的全局变量与网站中的全局变量相同。虽然最好是在jsfiddle的左上角菜单中使用 no wrap ,并拥有自己的 .ready()函数。否则,它会将您的代码包装在您网站上没有的 onload 函数中。

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.

这篇关于全球变量与jsFiddle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆