I use ajax to load data here is a function

$(document).on('change', '#Profile_id_category', function(){ var id = $(this).val() $.post('/todo/get1', {q:id}, function(data){ $('.list_tags').html(''); if(data !== null){ for(var i=0; data.data.length > i; i++){ $('.list_tags').append('<li class="tag">'+data.data[i].name+'<a class="del_tag"></a></li>'); } $('.list_tags').append('<li class="input_li_search"><input type="text" spellcheck="false" autocapitalize="off" autocorrect="off" autocomplete="off" style="width: 20px;" placeholder="" /></li>'); data_cache_edit = data.data; data_cache_real = data.data; } }, "json") }) 

I save the obtained data in two different arrays.

 data_cache_edit = data.data; data_cache_real = data.data; 

Then I make a delete event from the data_cache_edit array.

 $(document).on('click', '.del_tag', function(e){ index = $(this).parent().index(); $(this).parent().remove(); if(data_cache_edit.length > 0 && data_cache_edit[index]) delete data_cache_edit[index]; }) 

But for some reason, it is also deleted from the second data_cache_real array. I can’t understand how they are connected if I don’t even equate them anywhere

1 answer 1

JavaScript passes objects by reference. To untie two copies, you need to create a full copy of the array:

 var data_cache_edit = data.data.slice(0); 
  • Thank! did not know that the link is created by reference - modelfak