0

可能重复:
console.log 对象处于当前状态

我了解基本的同步和异步行为:

// this block gets executed all at once the next time the js engine can run it
setTimeout(function() { 
    var snacks = "cookies";
    snacks += "and popcorn";
    console.log("goodbye world"); 
}, 0);

console.log("hello world"); // this block runs before the block above

我不明白为什么这里的第一个控制台报告[]:

var x = [];
x.push({ a: "c" });
console.log(x); // says []
x.splice(0, 1);
console.log(x); // says []
4

1 回答 1

0

It's an issue of the console itself—it shows you the current value. The actual value is what you would expect. This behavior does not affect primitive values (strings, numbers, booleans, null, undefined) you log.

Try logging the array serialized.

var x = [];
x.push({ a: "c" });
console.log(JSON.stringify(x)); // says '[{"a":"c"}]'
x.splice(0, 1);
console.log(JSON.strinfigy(x)); // says '[]'

And just a note about the first code example: It is not completely correct that the first block gets executed second. The setTimeout call is made before the console.log call at the end—it's only the callback function passed to setTimeout that gets executed later.

于 2012-10-23T19:09:37.400 回答