简体   繁体   English

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

[英]How to push new elements in an array as they increase in number?

I have a gird with a few nodes.我有一个有几个节点的网格。 As I move my mouse on the gird, the values of row and col change.当我在网格上移动鼠标时, rowcol的值会发生变化。

For example:例如:

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

this code returns this on the console:此代码在控制台上返回:

在此处输入图像描述

These are the coordinates.这些是坐标。


The question is: How do I store these values in an array as they grow?问题是:随着它们的增长,如何将这些值存储在数组中? I tried to do it with the push function like this:我试着用这样的推 function 来做到这一点:

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

    console.log(coordinatesVisited);
  };

but it just returns me this:但它只是返回给我这个:

在此处输入图像描述

I want all these arrays in one single array at the end.我希望所有这些 arrays 最后放在一个数组中。 The grid is small so performance issues won't be any problem.网格很小,因此性能问题不会有任何问题。 The array can be overwritten again and again.数组可以一次又一次地被覆盖。

EDIT: With this code, 1-2 values are logged only while the log statement is inside the function but nothing stays.编辑:使用此代码,仅当日志语句位于 function 内时才会记录 1-2 个值,但没有任何内容。

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

    coordinatesVisited.push([row, col]);

  };
  console.log(coordinatesVisited);

Outside of the function, it is still an empty array.在 function 之外,它仍然是一个空数组。

This is probably a very simple question but right now I can't think of the solution.这可能是一个非常简单的问题,但现在我想不出解决方案。

Because each time const declare new array variable.因为每次 const 都声明新的数组变量。 So you need to declare array on before function call like global variable所以你需要在 function 像全局变量一样调用之前声明数组

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM