我正在请求应用程序上进行简单的 Cheerio 解析。不确定为什么在尝试设置数组时会出现此未定义的错误,但我猜测该值不存在可供设置。
var $ = cheerio.load(body);
var json = [
{ "range": "", "address": "", "state": "", "zip": "", "info": "" }
];
$('.findCourse').each(function (i, elem) {
// Range Name
console.log("iteration - ", i);
console.log("name - ", $(this).text().trim());
json[i].range = $(this).text().trim();
});
这是我的控制台响应,它读取并设置在抓取的 html 中找到的前两项。
iteration - 0
name - Pollock's Ferry Hunting Club Inc.
iteration - 1
name - Eagle 1
block 引用>TypeError: Cannot set property 'range' of undefined
at Object.<anonymous> (/usr/local/node_app/server.js:30:31) at exports.each (/usr/local/node_app/node_modules/cheerio/lib/api/traversing.js:267:24) at Request.request.post.form.__EVENTTARGET [as _callback] (/usr/local/node_app/server.js:26:30) at Request.self.callback (/usr/local/node_app/node_modules/request/request.js:121:22) at Request.EventEmitter.emit (events.js:98:17) at Request.<anonymous> (/usr/local/node_app/node_modules/request/request.js:978:14) at Request.EventEmitter.emit (events.js:117:20) at IncomingMessage.<anonymous> (/usr/local/node_app/node_modules/request/request.js:929:12) at IncomingMessage.EventEmitter.emit (events.js:117:20) at _stream_readable.js:920:16 1 May 23:02:57 - [nodemon] app crashed - waiting for file changes before starting...
最佳答案
发现问题了。在抛出引用错误之前正在执行调试语句。
简单的 javascript 数组问题,我试图将新元素插入数组中不存在的位置。
这是我的修复。
var $ = cheerio.load(body);
var json = [];
$('.findCourse').each(function (i, elem) {
// Range Name
json.push({});
json[i].range = $(this).text().trim();
});
关于json - 类选择器上的每个循环出现 Cheerio 错误 - TypeError : Cannot set property 'range' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23420154/