最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this Array is not saving the pushed elements each time the event is triggered? - Stack Overflow

programmeradmin2浏览0评论

I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

<button id="me">Click me to print form E to Z</button>


<script type="text/javascript">

      const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let myArray = [];
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>

I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

<button id="me">Click me to print form E to Z</button>


<script type="text/javascript">

      const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let myArray = [];
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>
Share Improve this question edited Feb 20, 2020 at 2:13 Shark Lasers 4717 silver badges15 bronze badges asked Feb 19, 2020 at 21:14 Kyle TechKyle Tech 617 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

The myArray variable is local to the function. Each time the function is called, it is initialized with a new array.

If you want to define the array once then you need to define it once and not every time the function is called (i.e. outside the function).

You need to initialize the array outside of the function, otherwise every time you call the function, it will be reset to []

<script type="text/javascript">

  let myArray = []; // create array here

  const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>
let myArray = []; // ARRAY STORED ONCE AS GLOBAL.
  const insertOptions = x=>{
    console.log(x);
 };
const circleInsertOptions = () => {
    let x = 48;
    myArray.push(48);
    console.log(myArray);
   return myArray;
};
  document.getElementById('me').addEventListener('click', circleInsertOptions);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论