0

I am trying to gradually populate an array inside an each function like this:

    $('#reference-select').change(function () {
        var intensity_list = new Array();
        var angle_list = new Array();
        $("#reference-select option:selected").each(function ()
        {
            $.get(window.location.origin+'/lims/upload/'+reference_list[$(this).val()]['File'], function(response) {
                data = response;
                // Split Data and refine
                lines = data.split('\n');
                let angle_arr = []
                let intensity_arr = [];
                for (var i = 0; i < lines.length; i++) {
                    cols = lines[i].split('\t');
                    angle_arr.push(parseFloat(cols[5]));
                    intensity_arr.push(parseFloat(cols[6]));
                }
                angle_arr = angle_arr.filter(Number.isFinite).slice(1);
                intensity_arr = intensity_arr.filter(Number.isFinite);
                if (angle_arr.length > 40) {
                    var top_reflexes = get_top_reflexes(angle_arr, intensity_arr, 10);
                } else if (angle_arr.length > 20) {
                    var top_reflexes = get_top_reflexes(angle_arr, intensity_arr, 3);
                } else {
                    var top_reflexes = get_top_reflexes(angle_arr, intensity_arr, 1);
                }
                angle_list.push(top_reflexes[0]);
                intensity_list.push(top_reflexes[1]);
            });
        });
        console.log([[1,2,3],[4,5,6]]); \\ This works as expected
        console.log(intensity_list);  \\ This produces strange output
        console.log(intensity_list[0]); \\ This results in undefined output
    });

Basically I push values from different files that the user can select in the #reference-select dropdown menu into the two arrays angle_list and intensity_list.

Now I would like to use the populated lists outside of the each function, but I experience very strange behavior. The line console.log(intensity_list); seems to work, but the resulting log looks strange in the console:

Strange output format for array

It should display the array similar to the line console.log([[1,2,3],[4,5,6]]);:

Expected output format

What is happening here? Why does it seem like intensity_list is not populated outside of each?

Axel
  • 1,415
  • 1
  • 16
  • 40
  • 1
    Nothing to do with `.each()`. it's the `.get()` which is asynchronous. Therefore, you're trying to access asynchronous value before it's populated. See[Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) and [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) for both aspects of what you've observed. – VLAZ Apr 22 '22 at 10:40
  • This is not a [mcve] – Andreas Apr 22 '22 at 10:40

0 Answers0