Output from an array?

  • 0
    Good afternoon, I'm trying to display an array, but something is wrong.
    The function itself:
    function init(){
        let template = `<li><a href="#">%name</a></li>`,
            search   = document.querySelector('#search'),
            list     = document.querySelector('#list'),
            names    = ['fff', 'aa'],
            render   = a => list.innerHTML = a.map(e => template.replace('%name', e)).join(`\n`);
    
        $.getJSON( "/ajax/country_ajax.php", function ( data, textStatus, jqXHR ) {
            data.forEach(function(item, i, arr) {
                names.push(item.name);
            });
        })
        search.addEventListener('input', function(e){
          let value = search.value.toLowerCase();
          render(names.filter(e => e.toLowerCase().startsWith(value)));
        });
        
        render(names);
    
        console.log(names);
    }


    0, 1 index can be seen that entered by hand and it is displayed. But why the entire array is not displayed is not clear.
    Is it the index or what?
    JavaScript Anonymous, Feb 20, 2019

  • 1 Answers
  • 0
    Wangyu: there are two elements in names, render displays them, and AFTER that, it processes the ajax request and adds other elements that you see in the console.

    put alert (1) before render (names) and alert (2) before data.forEach and check.



    On a good note, you would like to master the debugger and read something about asynchrony and event loop
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!