我设置了一个节点服务器,该服务器发出api请求并获取一些json数据。我正在尝试将某些数据提取到数组中,当我将结果发送到控制台时,它似乎正在工作,但是程序停止并给我一个错误。这是我的代码。
request(options, function (error, response, body) {
if (error) throw new Error(error);
var myArray = [];
bodies = JSON.parse(body);
let tag = '';
let bond = '';
let members = '';
for(var i = 0; i <= bodies.memberCount; i++){
let bond = bodies.members[i];
let smoke = bond.tag;
if(smoke === "undefined"){
return;
}else{
console.log(smoke);
}
}
});
the output in the console is this-
YYVPJ0G
2PJP89J2Q
9G8Y8022
JC90J0R
9LLYVQVQ
QV2R90V
JC9JVV
20RLC0QY
28LP0P8CG
2QYLGG9GY
2JRQQYQQJ
9YJVV0GJ
2RVP8U9
9VYG0VGQ
C2PGPYC
8CJ9CGG2
YGV0CRL
2VUV22VQY
R8G82YG
PPJUYQJ
28VYV2QJG
YC9LR0G9
8088RCYG
2JUJR2QVY
2YRPUC2Q
GJ0QP90
UGU9LR8
GJQRVC8C
UVVVJ80Q
LURGY8JV
2C9UJRP82
20J9VYVC0
82GUQLYRL
L2PCUYP
2CQUYPJRU
PYU98GU9
9QR2CCCLV
PP9V2P0
CGYLUG
8QLPJRYC2
Y2GYCLU
LQJ0QQ8
P2Y08LLP
P0RUVLG82
/home/phil/ClashApp/requests.js:34
let smoke = bond.tag;
^
TypeError: Cannot read property 'tag' of undefined
at Request._callback (/home/phil/ClashApp/requests.js:34:18)
at Request.self.callback (/usr/lib/nodejs/request/index.js:148:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/usr/lib/nodejs/request/index.js:896:14)
at emitOne (events.js:121:20)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous>
(/usr/lib/nodejs/request/index.js:847:12)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
它给出了我想要的所有结果,但是在我可以将所有myArray推入它们之前停止了程序。
答案 0 :(得分:1)
由于数组的编号从零开始,并且长度是数组中元素的数量,所以最后一个索引不是数组的长度,而是长度-1。
因此您需要将i <= bodies.memberCount
替换为i < bodies.memberCount
request(options, function (error, response, body) {
if (error) throw new Error(error);
var myArray = [];
bodies = JSON.parse(body);
let tag = '';
let bond = '';
let members = '';
for(var i = 0; i < bodies.memberCount; i++){
let bond = bodies.members[i];
let smoke = bond.tag;
if(smoke === "undefined"){
return;
}else{
console.log(smoke);
}
}
});
答案 1 :(得分:-1)
“ bond”不包含特定body.members [index]索引上的“ tag”键。
添加类似这样的支票。
if(bond.tag !== undefined)
smoke = bond.tag