Javascript - 变量失去其值(value)和 "becoming"未定义

标签 javascript jquery variables random

我似乎以某种方式丢失了变量 im 设置的值...

我尝试做的事情并不那么重要,所以我设置了一个(好评)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);

干杯
查理

最佳答案

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

改变:

get_link(count, not);

进入:

return get_link(count, not);

关于Javascript - 变量失去其值(value)和 "becoming"未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7219126/

相关文章:

javascript - 在 ExtJ 中绘制图形

jquery - jqPlot 日期轴 - 在错误的日期绘制条形图?

javascript - 制作事件的标签目标,而不是 img

c# - 是否可以将变量绑定(bind)到集合项

javascript - 通过点击html按钮更新html页面上的javascript变量?

javascript - AngularJS 分配不同的参数和函数

sql - 在 Oracle SQL 中声明要在查询中使用的变量

list - 如何在ansible list 文件中将列表值指定为变量?

javascript - 在屏幕外切换 div 进出

jQuery 如果 "this"包含