我理解基本的同步和异步行为:
// 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 []
答案 0 :(得分:0)
这是控制台本身的一个问题 - 它会显示当前值。实际价值是您所期望的。此行为不会影响您记录的原始值(字符串,数字,布尔值,null,undefined)。
尝试记录序列化的数组。
var x = [];
x.push({ a: "c" });
console.log(JSON.stringify(x)); // says '[{"a":"c"}]'
x.splice(0, 1);
console.log(JSON.strinfigy(x)); // says '[]'
只是关于第一个代码示例的注释:第一个块被执行第二个并不完全正确。 setTimeout
调用是在console.log
调用结束之前进行的 - 只有回调函数传递给后来执行的setTimeout
。