Home > Mobile >  How to update array in function
How to update array in function

Time:12-28

i have some problem with my array let me explain the issue first i want you guys see my codes to be on the same page

Note: this example code (not full version)

Code:

    let checked = []
 
    $.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&page=1&per_page=5", status => { createDiv(status, checked)})


    function createDiv(status, checked) {
       $(".checkbox").click(function (e) {
        if (!checked.some(i => i.id.includes($(this).attr('id'))) && checked.length < 3) {
           checked.push({
              id: $(this).attr('id'),
           })
        } else if (checked.some(i => i.id.includes($(this).attr('id')))) {
           checked = checked.filter(function (a) { return a.id != `${$(e.target).attr('id')}` })
        }})}

So when i click on checked it's push to array object and if i click on the same checked button it's filter the array because is already in array.

the problem is the array let checked = [] only update inside the function, what that means if i console.log checked inside function the array is filtered fine but if i console.log checked outside the array is not update

how can i update the array also outside function

i hope you guys have solution for me :)

CodePudding user response:

You declared checked in the function head. So checked exists in local scope. I think if you change the first checked from let checked = [] to var checked = [] and remove the checked in function head it should work.

var checked = []

function createDiv(status) {
   $(".checkbox").click(function (e) {
    if (!checked.some(i => i.id.includes($(this).attr('id'))) && checked.length < 3) {
       checked.push({
          id: $(this).attr('id'),
       })
    } else if (checked.some(i => i.id.includes($(this).attr('id')))) {
       checked = checked.filter(function (a) { return a.id != `${$(e.target).attr('id')}` })
    }})}

CodePudding user response:

The array will updated outside because it is a reference to a Array. The problem here is you must get data of the array after you click. It mean you must get data in callback at click function. Because this is a async so you only get data at the callback function if you want data is data that after clicked.

let checked = []

$.get("https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&page=1&per_page=5", status => { createDiv(status, checked)})


function createDiv(status, checked) {
   $(".checkbox").click(function (e) {
    if (!checked.some(i => i.id.includes($(this).attr('id'))) && checked.length < 3) {
       checked.push({
          id: $(this).attr('id'),
       })
    } else if (checked.some(i => i.id.includes($(this).attr('id')))) {
       checked = checked.filter(function (a) { return a.id != `${$(e.target).attr('id')}` })
    }
    console.log(checked);})}
  • Related