我正在从服务器获取 JSON 响应并创建一个 Javascript 对象。结构是这样的:
var response = {
key1:[],
key2:[],
key3:[],
key4:[],
key5:[]
}
当请求完成时,response
对象成功完成,如下所示:
Object (*expandable):
key1: Array[0]
key2: Array[0]
key3: Array[0]
key4: Array[20]
key5: Array[113]
现在我想将信息存储到数据库中。我已经创建了一个函数,并且我 console.log
响应对象以确保它没问题(这里它变得很有趣 - 请参阅评论):
function setupDatabase(){
console.log(response); // prints the response correctly (see response above)
console.log(response.key5); //prints key5: Array[0]. If I expand the Array[0] all the elements are inside.
console.log("key5: "+response.key5.length);//prints 0!!
}
前 3 个键为 0 是正常的,因为它们没有返回任何元素。其余2个都OK。为什么在同一对象上连续运行 3 个 console.log
命令时会收到此日志?我错过了什么吗?
最佳答案
这是 console.log
在某些浏览器上的工作方式的问题。您可能会考虑使用 console.log(JSON.stringify(response.key5))
来获取时间点 View 。
基本上,console.log
会记录某些内容的顶层,但是如果您稍后 展开其中一个内容,它会按原样显示内容>当你展开它时,而不是当你记录它时。所以 response.key5
是空的当你记录它时,但是在你在控制台中展开它之前添加了一些东西。
这种行为非常古怪。例如,在 Chrome 上,当 console.log
发生时,控制台是打开还是关闭可能很重要。如果您关闭了控制台,它会记录一个您无法展开的静态内容。
这是一个演示问题的简单示例。
在 Chrome 中:
- 确保控制台已关闭。
- 运行此代码段。
- 打开控制台。
您会看到该数组,如果展开它,您会看到在 console.log
行之后添加的条目。
var a = [];
console.log(a);
a.push("Hi there");
对比console.log(JSON.stringify(...))
:
var a = [];
console.log(JSON.stringify(a));
a.push("Hi there");
console.dir
执行类似于 console.log
的操作,但始终记录“实时”版本,即使控制台已关闭也是如此:
var a = [];
console.dir(a);
a.push("Hi there");
当您关闭控制台并稍后打开它时,console.dir
会显示带有展开箭头的 Array[1]
,然后会向您显示条目。但奇怪的是,如果您打开控制台,您会看到Array[0]
——但展开它会显示条目:
这种有点是有道理的,因为当你记录它时数组是空的,但是当你展开它时你会看到它的内容。
关于javascript - JSON 数组长度为零,即使有元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30255173/