0

I have a problem with a JavaScript variable.

<script type="text/javascript">
    jQuery(document).ready(function($){
        var numbers = [1,2,2,2]
    })
</script>
<script type="text/javascript">
    jQuery(document).ready(function($){
        console.log(numbers) 
    })
</script>

Console doesn't show anything. How can I use numbers in the second script?

EdenSource
  • 3,387
  • 16
  • 29
  • Check out this question: https://stackoverflow.com/questions/4862193/javascript-global-variables – Anthony Michael Cook Oct 12 '15 at 15:18
  • Possible duplicate of [What is the "best" way to set a global variable in JavaScript?](http://stackoverflow.com/questions/3352020/what-is-the-best-way-to-set-a-global-variable-in-javascript) – Subin Thomas Oct 12 '15 at 15:28

3 Answers3

0

If you want to use a variable between two script tags, you have to define it in the global scope. Also, you don't have anything named array? The following would work:

<script>
    var numbers = null;
    jQuery(document).ready(function($) {
        numbers = [1,2,2,2];
    });
</script>
<script>
    jQuery(document).ready(function($) {
        console.log(numbers);
    });
</script>
TbWill4321
  • 8,626
  • 3
  • 27
  • 25
0

No, you have defined numbers inside the scope of the first ready function, thus is not defined inside the second function. You would have to declare the variable outside of the function to give it the scope you need here. However, unless you have a reason to use 2 separate scripts here, I don't suggest it.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
0

i fixed it. I use "window.numbers = [1,2,2]" and then in the second script I call it "window.numbers". But i don't know when i use this way, it will good or not for performance.