Json 自增量数组销毁?Node.js
例如Json 自增量数组销毁?Node.js,json,node.js,Json,Node.js,例如 for (var i = 0; i < 5; i ++) { console.log(jsonfile[i].Username) } 我的JSON是: [ { "Username": "ozziep", "ProjectID": "ExpressJS", "TimeStamp": "2016-12-30T19:54:52.418Z", "Comments": "hello world how are
for (var i = 0; i < 5; i ++)
{
console.log(jsonfile[i].Username)
}
我的JSON是:
[
{
"Username": "ozziep",
"ProjectID": "ExpressJS",
"TimeStamp": "2016-12-30T19:54:52.418Z",
"Comments": "hello world how are we today?"
}
]
我正在使用require加载JSON 由于
jsonfile
中只有一个对象,因此jsonfile[1]
将是未定义的
使用i
代替i<5
,如下所示:
for (var i = 0; i < jsonfile.length; i ++)
{
console.log(jsonfile[i].Username)
}
for(var i=0;i
这就成功了,但感谢大家的投入
for( var user in jsonfile) {
console.log(jsonfile[user].Username);
console.log("------------------------")
console.log(jsonfile[user].Comments);
console.log("------------------------")
console.log(jsonfile[user].ProjectID);
console.log("------------------------")
console.log("")
}这将在第二个循环中失败,因为jsonFile[1]不存在数组中只有一项。。。因此,当您进入第二次迭代时,
jsonfile[1]
为空。请改用i
。投票结束,因为这是一个常见的新手错误。@Tom为什么在循环中使用固定长度而不是jsonfile.length
?这是一个片段,我有6个相同的,但内容不同。
for( var user in jsonfile) {
console.log(jsonfile[user].Username);
console.log("------------------------")
console.log(jsonfile[user].Comments);
console.log("------------------------")
console.log(jsonfile[user].ProjectID);
console.log("------------------------")
console.log("")