如何在数组中推送新元素随着数量的增加?

问题描述

我有一个带有几个节点的网格。当我在网格上移动鼠标时,rowcol 的值会发生变化。

例如:

  const handleMouseEnter = (row,col) => {
    console.log(row,col);
  };

代码在控制台上返回此内容

enter image description here

这些是坐标。


问题是:随着这些值的增长,我如何将它们存储在数组中?我尝试使用这样的推送功能来做到这一点:

  const handleMouseEnter = (row,col) => {
    const coordinatesVisited = [];
    coordinatesVisited.push(row,col);

    console.log(coordinatesVisited);
  };

但它只是返回给我:

enter image description here

最后我希望所有这些数组都在一个数组中。网格很小,所以性能问题不会有任何问题。数组可以一次又一次地被覆盖。

编辑: 使用此代码,仅当 log 语句位于函数内部时才会记录 1-2 个值,但不会保留任何内容

  const coordinatesVisited = [];
  const handleMouseEnter = (row,col) => {

    coordinatesVisited.push([row,col]);

  };
  console.log(coordinatesVisited);

函数之外,它仍然是一个空数组。

这可能是一个非常简单的问题,但现在我想不出解决方案。

解决方法

因为每次 const 都声明新的数组变量。所以你需要像全局变量一样在函数调用之前声明数组

 const coordinatesVisited = []; // declare as global
 const handleMouseEnter = (row,col) => {
    coordinatesVisited.push(row,col);
    console.log(coordinatesVisited);
  };