我有一堆 JavaScript 函数,它们在单击按钮时触发。因此假设我们有两个按钮触发两个方法,例如:
var universal = false;
var collection = Array(); // assume it has 5 data elements( 0...4) upon page load
function next()
{
if(universal)
addToArray();
// do whatever else
}
function addToArray()
{
console.log(collection);
// perform some DOM calls,that simply Hide/change position of elements
var newElement = 'some info';
collection.push(newElement);
}
在上面的 addToArray() 函数中,当单击“下一步”按钮并且通用变量设置为 true 时,会调用该函数。此时我们输入 addToArray() 方法,并调用 console.log 来检查“集合”。
在任何给定点,该元素不应超过 5 个,因为 addToArray 最终会将元素添加到集合中,但不是在开始时添加。但是,console.log 显示集合已添加新元素,该元素实际上应该在 addToArray 方法()期间添加,而不是立即添加。
我知道这听起来很愚蠢,但这就是我得到的。我试图了解异步行为是否与之有关。
最佳答案
如果您使用的是 Chrome,原因是 console.log
会记录对象的实时版本,当您稍后更改该对象时,该版本会在控制台窗口中更新。
如果你改变
console.log(collection);
...到
console.log(collection.join(","));
...或者可能更有用
console.log(JSON.stringify(collection));
...您将看到数组的时间点版本。
console.log 的行为实际上相当棘手,尽管一旦您了解它就会保持一致。例如,考虑以下代码:
var a = [1, 2, 3];
console.log("first");
console.log(a);
console.log("second");
a[0] = '11';
a = ['a', 'b', 'c'];
console.log("third");
如果运行时打开控制台,您会看到:
first [1, 2, 3] second third
...and no amount of clicking on that [1, 2, 3]
will show you the "11"
the code put at index 0
, much less the new array we put in a
.
But if you change the
var a = [1, 2, 3];
...到
var a = [[1, 1], 2, 3];
...你会看到这个:
first >[Array[2], 2, 3] second third
...然后单击数组旁边的箭头将其更改为:
first v[Array[2], 2, 3] 0: "11" 1: 2 2: 3 length: 3 __proto__: Array[0] second third
...这看起来有点无意义。
但是它确实有意义,您必须考虑控制台对您要求其输出的内容有引用。它输出该事物的一行,并且该行是静态的。但由于 Chrome 发现对象图变得更深,因此在数组旁边放置了一个箭头,以便您可以扩展它。当您单击数组时,通过查看对象的现在版本,将生成添加到输出的新行,该版本自第一行以来明显发生了变化被输出。很棘手,是吗?
在评论中,epascarello 提到使用 console.dir
来代替,但这只会使其更加可靠地“实时”,而不是作为时间点记录。
关于Javascript 不稳定的行为或我的错误代码,数组值在实际操作之前增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13923426/