在 Javascript 中动态创建数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3840960/
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-10-25 02:25:50  来源:igfitidea点击:

Dynamically create an array in Javascript

javascriptjson

提问by Lothar

I have an ajax request that returns some JSON formatted data. I'm building out a Google Maps display with it so I need to take that data and pass it to a few variables. So I want to build an array like:

我有一个 ajax 请求,它返回一些 JSON 格式的数据。我正在用它构建一个谷歌地图显示,所以我需要获取这些数据并将其传递给一些变量。所以我想构建一个数组,如:

var foo = [
    ['A Town', 32.844932, -50.886401, 1, setting1, '<div class="office"><div class="name">Smith</div><div class="location">111 Main Street<br /> Breen, MS<br /> 12345</div><div class="size">18 units<br />300 Foo</div><div class="thelink"><a href="#">Visit</a><br /><a href="#">Output</a></div></div>'],
    ['B Town', 33.844932, -51.886401, 2, setting1, '<div class="office"><div class="name">Jones</div><div class="location">112 Main Street<br /> Breen, MS<br /> 12345</div><div class="size">18 units<br />300 Foo</div><div class="thelink"><a href="#">Visit</a><br /><a href="#">Output</a></div></div>'],
[etc], 
[etc]
    ];

That I can then use to render my google maps locations. I have the JSON data so how do I loop through it and build out such an array? Or is there a better way to do it that I am missing (which is what I suspect, lol)?

然后我可以用它来呈现我的谷歌地图位置。我有 JSON 数据,那么如何遍历它并构建这样的数组?或者有没有更好的方法来做到这一点,我错过了(这是我怀疑的,哈哈)?

回答by Skilldrick

Just do:

做就是了:

var foo = [];
for (/*loop*/) {
    foo.push(['this is a new array', 'with dynamic stuff']);
}

回答by Robusto

In addition to Array.push(), you can also assign values directly to Array indices. For example,

除了 Array.push() 之外,您还可以直接为数组索引赋值。例如,

var foo = [];

foo[0] = "Foo 0";
foo[19] = "Bob";

This will give you a sparse array with a length of 20 and values in elements 0 and 19.

这将为您提供一个长度为 20 且元素为 0 和 19 的值的稀疏数组。

回答by Alex Wayne

You can use the pushfunction on Array objects to build them dynamically.

您可以push在 Array 对象上使用该函数来动态构建它们。

var a = [];
var b = [1,2,3,4,5,6,7,8,9];

for (var i=0; i<b.length; i++) {
  a.push(b[i]);
}