JcD*_*n86 3 javascript arrays json console.log
我从服务器获取JSON响应并创建Javascript对象.结构是这样的:
var response = {
key1:[],
key2:[],
key3:[],
key4:[],
key5:[]
}
Run Code Online (Sandbox Code Playgroud)
请求完成后,response对象成功完成,如下所示:
Object (*expandable):
key1: Array[0]
key2: Array[0]
key3: Array[0]
key4: Array[20]
key5: Array[113]
Run Code Online (Sandbox Code Playgroud)
现在稍后我想将信息存储到数据库中.我创建了一个函数,我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!!
}
Run Code Online (Sandbox Code Playgroud)
前3个键为0是正常的,因为没有为它们返回任何元素.剩下的2个还可以.为什么我得到这个日志,而我console.log连续在同一个对象上运行3个命令?我错过了什么吗?
这是如何console.log在某些浏览器上运行的问题.您可能会考虑使用console.log(JSON.stringify(response.key5)),以获取时间点视图.
基本上,console.log记录某些内容的顶层,但是如果稍后展开其中一个,它会显示扩展它时的内容,而不是记录它们时的内容.所以response.key5是空的,当你登陆它,但后来不得不添加的东西给它,你在控制台扩展它.
这种行为非常松懈.例如,在Chrome上,当console.log发生这种情况时,控制台是打开还是关闭可能很重要.如果您关闭控制台,它会记录您无法展开的静态内容.
这是一个展示问题的简单示例.
在Chrome中:
您将看到该数组,如果展开它,您将看到在该console.log行之后添加的条目.
var a = [];
console.log(a);
a.push("Hi there");Run Code Online (Sandbox Code Playgroud)
对比console.log(JSON.stringify(...)):
var a = [];
console.log(JSON.stringify(a));
a.push("Hi there");Run Code Online (Sandbox Code Playgroud)
console.dir执行类似的操作console.log,但始终记录"实时"版本,即使控制台已关闭:
var a = [];
console.dir(a);
a.push("Hi there");Run Code Online (Sandbox Code Playgroud)
当控制台关闭时,稍后再打开它,console.dir显示Array[1]扩展箭头,然后显示该条目.但奇怪的是,如果您打开控制台,您会看到Array[0] - 但随后展开它会向您显示条目:

这种情况很有意义,因为当你记录它时数组是空的,但是当你展开它时你会看到它的内容.
| 归档时间: |
|
| 查看次数: |
2509 次 |
| 最近记录: |