Javascript - Variable losing its value and "becoming" undefined
I seem to somehow be losing the value of a variable im setting...
What im trying to do is not so important, so I've set up a (Well commented) jsFiddle to show you what im getting. Also the code is below.
If anyone can see whats going on any help is appreciated :)
See jsFiddle > http://jsfiddle.net/qNWuV/4/ < Recommend you take a look here
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);
Cheers
CharlieYou are not returning the value from the recursive call.
Change:
get_link(count, not);
into:
return get_link(count, not);
In the get_link
function, you are traversing the nots
array using for / in. You should use a regular for loop.
精彩评论