当我运行这段代码时:
var a = ['a','b','c'];
var b = ['a','b','c'];
for(i = 0; i <= a.length-1; i++){
b.shift();
console.log(b);
}
我期望这样的输出:
['b','c']
['c']
[]
但是我得到了这个输出:
[]
[]
[]
为什么?
我如何获得预期的输出?
最佳答案
这是一个 known problem in Chrome .这是因为 console.log
不会复制您想要显示的内容,它只是存储引用。
由于日志不会立即更新,但是一旦您的函数结束并且浏览器更新了用户界面,日志将显示 b
变量的当前状态,而不是每个 时的状态code>console.log
已调用。
要获得所需的输出,您必须为每个 console.log
调用制作变量状态的闪存副本:
console.log(b.toString());
关于javascript - 如何在循环内使用 shift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8635615/