0
export default function App() {
  const arr1 = [{ color: "black", stake: 700 }];
  const arr2 = [];

  const click = () => {
    arr2.push(arr1);
    // console.log(arr2);
  };

  console.log(arr2); //-> my question is why this one always is []? how to add item inside when i click

  //   var result = [];
  // for (var i=0; i < 10; i++) {
  //      result.push(i);
  // }
  // console.log(result);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={click}>addItem</button>
    </div>
  );
}

https://codesandbox.io/s/friendly-galileo-fr3mqb?file=/src/App.js

need to click add arr1 inside arr2, return outside to change arr2

yuanyuan
  • 11
  • 1
  • Because when you log it, it's been created but nothing has ever pushed anything to it (yet). No `click` can be processed between the `const arr2 = [];` statement and the `console.log` statement. You probably meant to store `arr2` (if not both `arr1` and `arr2`) in some form of state storage (for instance, if this is a React project, via [`useState`](https://react.dev/reference/react/useState) or similar). – T.J. Crowder Mar 29 '23 at 15:12

0 Answers0