Javascript数组日志混乱 [英] Javascript Array logging confusion

查看:152
本文介绍了Javascript数组日志混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到一些我不能理解的东西。我在JavaScript中做一些非常简单的事情:

I have noticed something that I cannot understand at all. I am doing something really simple in JavaScript:

var a = [1,2,3];

console.log(a.push(4));
console.log(a);
console.log(a.push(5));

我希望控制台记录: 4 [1,2,3,4] 和 5 此处
实际的控制台输出如下: 4 [1,2,3,4,5] 5

I would expect the console to log: 4, [1,2,3,4], and 5 as described here for example. The catch is that the actual console output looks like: 4, [1,2,3,4,5], and 5

请参阅: http://jsfiddle.net/HknMF/

实际上, 5

What on earth makes the 5 appear in the second log output?

:fwiw这里是Firebug的屏幕截图,显示了两种行为: http://i.imgur.com/fwAK3.png

EDIT: fwiw here's a screenshot of Firebug showing both behaviors: http://i.imgur.com/fwAK3.png

推荐答案

在某些浏览器中的控制台使用对数组/对象的引用,并且在 console.log()调用后更改的对象会看到已更改的对象。

The console in some browsers uses a reference to the array/object, so when you inspect it and the object changed after the console.log() call you'll see the changed object.

这也发生在对象,但不是为内联显示的数组:

In Firefox this also happens for objects, but not for arrays which are displayed inline anyway:

>>> var a = [1,2,3]; console.log(a.push(4)); console.log(a); console.log(a.push(5));
4
[1, 2, 3, 4]
5

特别是对于不包含函数的对象,快速解决方法是克隆它们(如果你有jQuery,则日志 $。extend({},yourObject)字符串版本(那么你失去了好的对象视图,只是得到一个纯字符串)。使用 a.slice(0)

Especially for objects that do not contain functions a quick workaround is either cloning them (log $.extend({}, yourObject) if you have jQuery) or logging their JSON string version (then you lose the nice object view and just get a plain string though). An array can easily cloned (shallow copy!) using a.slice(0)

这篇关于Javascript数组日志混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆