如何在循环内使用shift?

时间:2021-09-05 09:08:09

When I run this code:

当我运行此代码时:

var a = ['a','b','c'];
var b = ['a','b','c'];

for(i = 0; i <= a.length-1; i++){
    b.shift();
    console.log(b);
}

I expected this output:

我期待这个输出:

['b','c']
['c']
[]

But I get this output:

但我得到这个输出:

[]
[]
[]

Why?

And how do I get my expected output?

我如何获得预期的输出?

3 个解决方案

#1


7  

This is a known problem in Chrome. It's because the console.log doesn't make a copy of what you want to display, it just stores the reference.

这是Chrome中的已知问题。这是因为console.log没有复制你想要显示的内容,它只是存储引用。

As the log isn't updated immediately, but once your function ends and the browser updates the user interface, the log will show the current state of the b variable, not the state when each console.log call was made.

由于日志不会立即更新,但是一旦您的功能结束并且浏览器更新了用户界面,日志将显示b变量的当前状态,而不是每个console.log调用时的状态。

To get the desired ouput you would have to make a flash copy of the state of the variable for each console.log call:

要获得所需的输出,您必须为每个console.log调用制作变量状态的flash副本:

console.log(b.toString());

#2


1  

This is a side-effect of the console.log statements not being printed as the statements are executed. Note that if you replace your console.log with alert, the code works as expected.

这是在执行语句时未打印的console.log语句的副作用。请注意,如果使用alert替换console.log,则代码将按预期工作。

#3


0  

Or change the log paramater to be an expression as per my answer to Javascript Funky array mishap

或者根据我对Javascript Funky数组事故的回答,将日志参数更改为表达式

console.log ('' + b);

#1


7  

This is a known problem in Chrome. It's because the console.log doesn't make a copy of what you want to display, it just stores the reference.

这是Chrome中的已知问题。这是因为console.log没有复制你想要显示的内容,它只是存储引用。

As the log isn't updated immediately, but once your function ends and the browser updates the user interface, the log will show the current state of the b variable, not the state when each console.log call was made.

由于日志不会立即更新,但是一旦您的功能结束并且浏览器更新了用户界面,日志将显示b变量的当前状态,而不是每个console.log调用时的状态。

To get the desired ouput you would have to make a flash copy of the state of the variable for each console.log call:

要获得所需的输出,您必须为每个console.log调用制作变量状态的flash副本:

console.log(b.toString());

#2


1  

This is a side-effect of the console.log statements not being printed as the statements are executed. Note that if you replace your console.log with alert, the code works as expected.

这是在执行语句时未打印的console.log语句的副作用。请注意,如果使用alert替换console.log,则代码将按预期工作。

#3


0  

Or change the log paramater to be an expression as per my answer to Javascript Funky array mishap

或者根据我对Javascript Funky数组事故的回答,将日志参数更改为表达式

console.log ('' + b);