Javascript 如何在javascript中声明和初始化全局数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11262666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:11:53  来源:igfitidea点击:

how to declare and initialize global arrays in javascript

javascriptarraysglobal

提问by user25

In my html code, I need a global array which I use throughout my application. How to create and initialize global array variable in javascript..

在我的 html 代码中,我需要一个在整个应用程序中使用的全局数组。如何在javascript中创建和初始化全局数组变量..

回答by gion_13

You can do it several ways :
In the global scope :

您可以通过多种方式做到这一点:
在全局范围内:

var arr = [];

Binding the array to the global namespace:

将数组绑定到全局命名空间:

window.arr = [];

or, for running the code in other environments, where the global object is not necessarily called window:

或者,为了在其他环境中运行代码,全局对象不一定被调用window

(function(global){
    global.arr = [];
})(this);

回答by J?rgen

In the browser, you can attach objects to the global scope using the window object:

在浏览器中,您可以使用 window 对象将对象附加到全局范围:

window.myArray = ["foo", "bar"];

In Node.js, you can access the global scope using the globalobject.

在 Node.js 中,您可以使用global对象访问全局范围。