Javascript - 变量失去其价值并“变得”未定义

时间:2011-08-28 05:01:17

标签: javascript jquery variables random

我似乎在某种程度上失去了变量即时设置的价值......

我想要做的事情并不那么重要,所以我设置了一个(评论很好的)jsFiddle来向你展示我的成果。代码如下。

如果有人能看到有什么帮助,那么我们将不胜感激:)

参见jsFiddle> http://jsfiddle.net/qNWuV/4/<建议你看看这里

var habs = ["417,77", "410,363", "388,433", "262,435", "262,210", "391,101", "384,183", "61,114", "331,171", "164,433", "361,248", "302,329", "154,307", "410,350", "173,298", "308,429"]; //just an array of co-ords for another part of my app. Only the .length is used below.

//############################
// NOTE: as this problem depends on random numbers you MAY not see it. If "undefined" is ANYWHERE in the Result, the problem is occurring, otherwise re-run the code.
//############################


function link_habs(habs) {
    var test2 = '';
    var hab_length = habs.length;
    for (var e in habs) {
        var hab_link_1 = get_link(hab_length, e + ',');
        var hab_link_2 = get_link(hab_length, e + ',' + hab_link_1);
        document.write('<br /><br />each1: ' + hab_link_1); //Variable lost?
        document.write('<br />each2: ' + hab_link_2 + '<br />'); //Variable lost?
        test2 += e + ':' + hab_link_1 + ',' + hab_link_2 + '<br />';
    }
    document.write('<br /><br /><br />' + test2);
}

function get_link(count, not) {
    var nots = not.split(',');
    for (var i in nots) { nots[i] = parseInt(nots[i], 10); }
    var hab_link = Math.floor(Math.random() * count);
    if (nots.indexOf(hab_link) === -1) {
        document.write('<br />returned: ' + hab_link); //Variable is intact HERE
        return hab_link;
    } else {
        get_link(count, not);
    }
}

link_habs(habs);

干杯
查理

2 个答案:

答案 0 :(得分:6)

您没有从递归调用返回值。

变化:

get_link(count, not);

成:

return get_link(count, not);

答案 1 :(得分:1)

get_link函数中,您使用for / in遍历nots数组。您应该使用常规for循环。