【发布时间】:2017-01-06 05:11:47
【问题描述】:
我正在编写一个网络爬虫,它使用正则表达式来提取段落中的信息并将其存储在一个对象中。然后我将对象添加到数组中。这是我的完整代码:
function scrapeCourseData(htmlString) {
// scrapes a specific department's course list
var tempArr = [];
console.log(tempArr); // outputs '[]'
$ = cheerio.load(htmlString);
// #coursestextcontainer contains the actual information for every single course listed in a department
$('#coursestextcontainer').find('.courseblock').each(function(i, elem) {
// finds all divs of type courseblock, iterates though each of them,
// extracting course information from children.
console.log('courseblock ' + (i + 1));
var courseText = $('strong', '.courseblocktitle', elem).text(); // Gets the text that will be parsed
var regex = /([A-Z]{4}\s[A-Z]{1,2}\d{4})\s(.*?)(?:\.*)(\d{1,2}(?:\.?|-?)\d{0,2}\spoints?)/g;
var regexGroups = Object.freeze({
NUMBER: 1,
NAME: 2,
CREDITS: 3
});
var match, course;
while ((match = regex.exec(courseText)) !== null) { // when regex.exec returns null, no more matches, and loop stops.
course = {
number: match[regexGroups.NUMBER],
name: match[regexGroups.NAME],
credits: match[regexGroups.CREDITS]
};
tempArr.push(course); // doesn't work-- result is array full of 'null'
console.log(course); // but this outputs as a valid object, e.g. { number: 'AFAS W3030'... }
}
});
console.log("Complete tempArr: " + tempArr); // outputs [object Object],[object Object],[object Object], etc.
for (var j of tempArr) {
dataJSONObject.push(tempArr[j]);
console.log('\ntempArray at ' + j + ': ' + tempArr[j]); // outputs [object Object]: undefined
}
console.log('\n');
}
当我第一次将tempArr 定义为[] 并将其输出到控制台时,我得到了预期的结果[]。
我从正则表达式匹配形成的对象在运行时也如预期的那样有效。
但是,当我尝试将这些对象推送到tempArr,然后打印tempArr 时,它输出为undefined。
我一直在探讨其他 stackoverflow 问题,我很确定我的问题是当我推送到 tempArr 时,我这样做超出了它的范围。我已经尝试在我声明tempArr 的地方移动(例如,通过将其置于其函数之外以使其成为全局),但在推送后我仍然得到undefined。我错过了什么?
【问题讨论】:
-
tempArray 是
JSON而不是console.log("Complete tempArr: " + tempArr);试试console.log("Complete tempArr: " + JSON.stringify(tempArr));
标签: javascript arrays object undefined push