0

I create a array in start of my js,and define button,when click the button a for loop must push some element to array,but console log show null at end. I want get for data in global variable and use it every where

    var TableName = [];
    $(function(){
        $("#SecondButton").on('click',function(){
            var TableName = [];

            $(".Review").find("input:text").each(function(index,el){
                TableName.push(el.value);
            });
        });
    });
    console.log(TableName);
});
nima
  • 502
  • 5
  • 14
  • The code above declares **two** variables called "TableName". – Pointy Feb 08 '17 at 23:02
  • yes i want when user click again on button array fill with new data – nima Feb 08 '17 at 23:03
  • 1
    Even if the inner variable wasn't declared, the `console.log` at the end would show an empty array. The `click` event handler is executed *some time in the future* (when a click event occurs) **after** `console.log` was called. If you move `console.log` inside the handler you will get the output you expect. – Felix Kling Feb 08 '17 at 23:04
  • to use your array as global simply declare it once in global scope, then just assign value in your function (another declaration with "var" keyword make another variable in the function scope) [fiddle](https://jsfiddle.net/scraaappy/8yhzxmmu/) – scraaappy Feb 08 '17 at 23:22

0 Answers0