Node JS for循环不起作用

时间:2014-03-27 00:36:41

标签: node.js

在节点js中,运行for循环后,descriptp不包含任何内容,没有字段写入descrip数组,为什么?

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);
};

2 个答案:

答案 0 :(得分:2)

JavaScript中数组的长度由length属性返回:

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);
};

另外,正如@Red Alert的评论中指出的那样,你在for循环中覆盖了你的data变量(JavaScript没有块范围的概念)。我已将其重命名为_data,但您可能会想出一个更有意义的名称来区分数组和当前迭代的元素。

答案 1 :(得分:2)

假设您希望data成为数组,data.size - 1将为-1,因为data.sizenull。所以它会立即退出循环。您可能需要data.length