Javascript 分析node.js中的数组时出错,无法访问该数组的成员
我是node.js的新手,我用两条insert语句编写了一段代码,在postman中使用了json输入 但在执行之后,我无法访问该数组的成员,但是可以访问其他属性name、price,我不明白为什么json中的玩家不能被访问并显示未定义 结果在控制台 以下是我在《邮递员》中的尝试:Javascript 分析node.js中的数组时出错,无法访问该数组的成员,javascript,node.js,Javascript,Node.js,我是node.js的新手,我用两条insert语句编写了一段代码,在postman中使用了json输入 但在执行之后,我无法访问该数组的成员,但是可以访问其他属性name、price,我不明白为什么json中的玩家不能被访问并显示未定义 结果在控制台 以下是我在《邮递员》中的尝试: { "userid": 41, "name": "dhya", "price": 11, "
{
"userid": 41,
"name": "dhya",
"price": 11,
"players": [
{
"id":1,
"firstname":"aa",
"lastname":"ee",
"position":"df",
"price":12.1,
"appearences":2,
"goals":1,
"assists":1,
"cleansheets":1,
"redcards":1,
"yellowcards":1,
"image":"qq",
"clubid":2
},
{
"id":2,
"firstname":"aa",
"lastname":"ee",
"position":"df",
"price":12.1,
"appearences":2,
"goals":1,
"assists":1,
"cleansheets":1,
"redcards":1,
"yellowcards":1,
"image":"qq",
"clubid":2
}
]
}
下面是我在node.js中尝试的内容
create:(data,callback)=>{
var myArray = [];
for(item in data.players[0]) {
console.log(item.id);
}
var idsArray = myArray.map((obj) => obj.userid);
var id;
console.log(id);
pool.query(
'insert into club(userid,name,price) values(?,?,?)',
[
data.userid,
data.name,
data.price
],
/* 'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) IN (?,?,?,?,?,?,?,?,?,?,?,?,?)',
[
myArray.id,
myArray.firstname,
myArray.lastname,
myArray.position,
myArray.price,
myArray.appearences,
myArray.goals,
myArray.assists,
myArray.cleansheets,
myArray.redcards,
myArray.yellowcards,
myArray.image,
idsArray,
],*/
(error,results,fields)=>{
if(error){
callback(error);
}
id = results.insertId;
return callback(null,results);
},
pool.query(
'insert into players(id,firstname,lastname,position,price,appearences,goals,assists,cleansheets,redcards,yellowcards,image,clubid) IN (?,?,?,?,?,?,?,?,?,?,?,?,?)',
[
myArray.id,
myArray.firstname,
myArray.lastname,
myArray.position,
myArray.price,
myArray.appearences,
myArray.goals,
myArray.assists,
myArray.cleansheets,
myArray.redcards,
myArray.yellowcards,
myArray.image,
idsArray,
],
(error,results,fields)=>{
if(error){
callback(error);
}
// id = results.insertId;
return callback(null,results);
},
),
);
},
问题是json中的玩家数据无法访问,我这样循环只能得到玩家的索引
for(item in data.players) {
console.log(item);
}
假设您使用的是Node.js 8或更高版本,那么您可以将
替换为。。。在
中,使用用于。。。属于
for(let player of data.players) {
console.log(player);
}
如果需要访问json上的对象:
myJson.userId
myJson.name
myJson.price
如果需要访问“玩家”中的对象:
哦,我可以访问,但是数组没有推送json
myJson.players.forEach((player) => {
// now you can access to every player
// example: console.log(player.id)
})