This is someone else's code which I'm trying to modify to make it not use global variable. I've been pulling my hair though unable to make this work.
The original code is:
http://jsfiddle.net/t4p9G/
The code uses global variable 'body' which I'm trying to avoid. The function does not use 'return' statement.
I tried to modify this to not use global variable and use return statement but it doesn't then walk all the nodes. It seems to stop after finding the first value:
http://jsfiddle.net/t4p9G/62/
Why is that? What am I missing?
The original code is:
http://jsfiddle.net/t4p9G/
The code uses global variable 'body' which I'm trying to avoid. The function does not use 'return' statement.
Code:
var body = '';
function scan(obj)
{
var k;
if (obj instanceof Object) {
for (k in obj){
if (obj.hasOwnProperty(k)){
body += 'scanning property ' + k + '<br/>';
scan( obj[k] );
}
}
} else {
body += 'found value : ' + obj + '<br/>';
};
};
scan(testJSON);
document.getElementById('output').innerHTML = body;
I tried to modify this to not use global variable and use return statement but it doesn't then walk all the nodes. It seems to stop after finding the first value:
http://jsfiddle.net/t4p9G/62/
Code:
function scan(b, obj)
{
var k;
if (obj instanceof Object) {
for (k in obj){
if (obj.hasOwnProperty(k)){
b += 'scanning property ' + k + '<br/>';
return scan(b, obj[k] );
}
}
} else {
return b+'found value : ' + obj + '<br/>';
};
};
var body='';
var body= scan(body, testJSON);
document.getElementById('output').innerHTML = body;
Why is that? What am I missing?