简体   繁体   中英

Create a global variable in JavaScript

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?

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>

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM