JavaScript命名空间是否被污染了

Is javascript namespace polluted?

本文关键字:污染 是否 命名空间 JavaScript      更新时间:2023-09-26

我对 js 命名空间没有很好的掌握,并且正在对标题进行 WAGing*,但这是我对正在发生的事情的猜测之一。

  • WAG = 疯狂猜测

我的应用程序崩溃了(戏剧性地);试图找出原因。 事实上,在 3 个 Q/A 对之后,它炸毁了整个 Chrome 标签..!我开始怀疑我在代码中做错了什么......

警告:在运行这些 jsFiddles 之前保存您的浏览会话。(在Chrome中,jsFiddle只会炸毁自己的标签,但我无法评论其他浏览器)

jsFiddle One
jsFiddle Two - 以防万一 jsFiddle One 被吹走的欺骗

请帮助我确切地理解我今天犯下了哪些壮观的白痴主义。

.HTML:

<div id="result">
    <div class="truth tr0"><h2>---</h2></div>
    <div class="truth tr1"><h2>answer to one</h2></div>
    <div class="truth tr2"><h2>answer to two</h2></div>
    <div class="truth tr3"><h2>answer to three</h2></div>
    <div class="truth tr4"><h2>answer to four</h2></div>
 </div>   
<div id="replaceLink">
    <div class="youcould yc1">
        <a href="#2"><h2>QUESTION ONE</h2></a>
    </div>
    <div class="youcould yc2">
        <a href="#3"><h2>QUESTION TWO</h2></a>
    </div>
    <div class="youcould yc3">
        <a href="#4"><h2>QUESTION THREE</h2></a>
    </div>
    <div class="youcould yc4">
        <a href="#5"><h2>QUESTION FOUR</h2></a>
    </div>
    <div class="youcould yc5">
        <a href="#6"><h2>THANK YOU</h2></a>
    </div>
</div>
<div id="response"></div>
<input type="button" id="mybutt" value="Start Test" />

Javascript/jQuery:

var cnt = 0;
var window = {};
window.arrDone = [];
function nextQues() {
    if (window.arrDone.length == 4) return 5;
    success = 0;
    while (success == 0) {
        nn = Math.floor(Math.random() * 3) + 1;
        if (window.arrDone.indexOf(nn) == -1 && nn != 5) {
            success++;
            window.arrDone.push(nn);
        }
    }
    return nn;
}
$('.youcould, .truth').hide();
$('.tr0').show();
$('.youcould').click(function() {
    $(this).hide();
    thisA = window.arrDone[window.arrDone.length -1];
    $('.tr'+thisA).show();
});
$('.truth').click(function() {
    $(this).hide();
    nextQ = nextQues();
    $('.yc'+nextQ).show();
});
$('#mybutt').click(function () {
    $(this).hide();
    $('.tr0').hide();
    nextQ = nextQues();
    $('.yc'+nextQ).show();
});

我的猜测是

var window = {};

window很特殊,因此创建一个名为 window 的全局变量会招致麻烦。

你的 while 循环在第三次传递时无限运行,因为它不满足条件。

在某些时候,arrDone将包含由随机生成器产生的数字123(顺便说一句,它永远不会产生5)。在这种情况下,nextQues() 不会中止并返回 5(如 arrDone.lenght == 3 ),并将进入循环。你的随机生成器只产生数字 123 ,它们总是已经在数组中,所以 if 条件(将结束循环)永远不会满足。你有一个生成随机数的无限循环。

我猜你想要

function nextQues() {
    var l = 4;
    if (window.arrDone.length >= l)
        return l+1;
    while (true) {
        var nn = Math.floor(Math.random() * l) + 1; // generate 1, 2, 3 or 4
        if (window.arrDone.indexOf(nn) == -1) {
            window.arrDone.push(nn);
            return nn;
        }
    }
}