-1

I am trying to empty JavaScript array which is declared globally. Here is my code-->

var arr = [];
var store = [];
var result_count = '';
var result = '';
var store_count = '';

$('select').on('change', function() {
    arr.push(this.value);
    var record_count = arr.length;
    for (var i = 0; i < record_count; i++) {
        store[i] = arr[i].split("-");
    }
    store_count = store.length;
});

$("#save_seting_permission").click(function() {
    $.ajax({
        type: 'post',
        dataType: 'JSON',
        url: base_url + "admin/permission_submit",
        data: {
            result: JSON.stringify(store),
            result_count: store_count
        },
        success: function(result) {
            /* while(store.length > 0) 
            {
                store.pop();

            } */
            store.length = 0;
            //console.log(store);
        },
    });
});

array named store declared globally. I am pushing values on change event of drop down, & sending values to database in ajax submission & clearing(emptying) array. Next time again when I am pushing values to array, old values are still there in array(though I have cleared it in ajax success).

2 Answers2

1

Why do you not use just this?

store = [];

This empties the array without any doubts. It's an assignment of new empty array rather than modifying the old array.

Here you have a list of a few methods how to empty an array - How do I empty an array in JavaScript?. Though the solution you have provided is valid and I don't see any reason why it should not work.

Community
  • 1
  • 1
MelkorNemesis
  • 3,415
  • 2
  • 20
  • 20
0

After success callback u can just guive new value to your array :

success: function(result) { store = [];}
splifo
  • 45
  • 5