1

In node js, after running the for loop, descrip does not contain anything, no field written into the descrip array, why?

data = data['data'];
var course = data['course'];
data = data['sections'];
var descrip = new Array();
console.log(data.length);
for (var i = data.size - 1; i >= 0; i--) {
    var data = data[i];
    var section = data['section'];
    var day = data['day'];
    var date = data['date'];
    var start = data['start_time'];
    var end = data['end_time'];
    var location = data['location'];
    var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
    descrip.push(res);
};
1
  • Don't you mean data.length? You're referring to data.size there. Using forEach(...) largely avoids this. Commented Mar 27, 2014 at 0:39

2 Answers 2

2

Assuming you expect data to be an array, data.size - 1 will be -1 since data.size is null. So it will exit the loop immediately. You probably want data.length.

Sign up to request clarification or add additional context in comments.

1 Comment

In Ruby size and length are synonymous, so this is easy to miss.
2

The length of an array in JavaScript is returned by the length property:

for (var i = data.length - 1; i >= 0; i--) {
     // no block scope in JS, using data as a variable name here overwrites array
    // var data = data[i];
    var _data = data[i];
    var section = _data['section'];
    var day = _data['day'];
    var date = _data['date'];
    var start = _data['start_time'];
    var end = _data['end_time'];
    var location = _data['location'];
    var res = 'Section: '+section+'\nDate: '+date+' '+day+'\nLocation: '+location+'\nStart: '+start+'\tEnd: '+end;
    descrip.push(res);
};

Also, as pointed out in the comments by @Red Alert, you're overwriting your data variable in the for loop (JavaScript has no concept of block scope). I've renamed it _data, but you could probably come up with a more meaningful name to distinguish between the array and the element of the current iteration.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.