console.log更改数组长度(容量)

问题描述 投票:0回答:2

我很难理解为什么console.log()的位置会影响我的数组的容量。这是小提琴:https://jsfiddle.net/xbqph81e/4/

这是代码:

const pressed = [];
const secretCode = '123456';

window.addEventListener('keyup', (e) => {
  console.log(e.key);
  pressed.push(e.key);

  console.log("First Log",pressed); //console.log here = array has capacity of 7 characters
  pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length);

  //console.log("Second Log",pressed); //first console.log is commented and this uncommented = array has capacity of 6 characters
});
.as-console-wrapper { max-height: 100% !important; top: 0; }

有谁知道为什么会这样?

javascript arrays console.log
2个回答
0
投票

在第一个console.log中,你刚刚将新键推送到数组,所以此时它的长度为7。

之后,调用.splice使数组的长度与秘密相同(在本例中为6),因此在此之后数组的长度只有6。

并且console.log将(大多数时候)在该点显示该变量的值,恰好是长度为6的数组。


0
投票

console.log不会改变你的阵列。它正在被修改,因为splice()方法更改了数组。您可以尝试使用slice()方法,而不是返回一个新数组。如果您选择这样做,则需要分配从pressed.slice()返回的数组。

© www.soinside.com 2019 - 2024. All rights reserved.