Javascript 如何在数组中推送数组而不是连接?

Javascript 如何在数组中推送数组而不是连接?,javascript,php,arrays,Javascript,Php,Arrays,下面的php代码给出了一个名为“markers”的数组变量 正如您在上面的代码中所看到的,我尝试使用简单的双括号[[]],但这不起作用。 如何正确地做到这一点? 非常感谢你的帮助 附言: 如果有人觉得有必要否决我的问题,请告诉我原因,这样我可以学到一些东西。由于评论: 警报([[1,2][3,4]])将弹出错误的1,2,3,4 警报(JSON.stringify([[1,2][3,4]])将弹出[[1,2],[3,4] .push([1,2])将向标记添加一个数组:[[1,2],[3,4],[5

下面的php代码给出了一个名为“markers”的数组变量

正如您在上面的代码中所看到的,我尝试使用简单的双括号[[]],但这不起作用。 如何正确地做到这一点? 非常感谢你的帮助

附言: 如果有人觉得有必要否决我的问题,请告诉我原因,这样我可以学到一些东西。

由于评论:
警报([[1,2][3,4]])
将弹出错误的
1,2,3,4

警报(JSON.stringify([[1,2][3,4]])
将弹出
[[1,2],[3,4]

.push([1,2])
将向
标记添加一个数组:[[1,2],[3,4],[5,6]
.push(1,2)
元素添加到
标记中:[1,2,3,4,5,6]

但更好的方法是不要执行javascript
.push
(节省客户端CPU时间)
用以下方式在javascript中定义数组:

window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
  ["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];

发布预期的输出和输入您会看到数组被连接,因为您正在向数组发出警报,该数组在发出警报后将调用加入数组的toString()函数。请尝试使用
console.log(window.markers)
在控制台中,您应该可以看到数组结构。您不需要双括号。单括号是一个合适的用法:
window.markers.push(['arrayItem1','arrayItem2']);
。使用
console.log(window.markers)
检查您的输出。或者,如果您仍然喜欢使用alert,请使用alert(JSON.stringify(window.markers));查看数组结构。你们都非常正确!哇,今天学到了一些东西。事实上,我的代码一直都很有效,只是因为“错误”的警告消息,我才停止完成它!谢谢!!您可以再插入一些括号来分隔数据集;直接在
while(…)
和之前的
endwhile
。最后一个逗号无关紧要。这个答案中最初发布的代码的结果不是我想要的。我需要括号内的数组作为数据集。@Nina:我想这就是我需要的,但我恐怕不知道括号到底放在哪里。顺便问一下:为什么push方法不好?因为它为我提供了所需的输出。@Garavani数据集的意思是你想要{'center_name':'First center','center_address':'First address',…}?推送是不好的,因为它需要执行。如果你可以创建普通脚本来保存一些客户端CPU活动,为什么你需要它?请准确地显示你需要的。@Garavani:here
[“谢谢大家。我会坚持使用推送解决方案(是ACF插件的人为解决这个问题而给我的解决方案。它工作得很好。用befzzs代码尝试了一些东西,但没有成功。要准确显示我需要的内容,请参阅原始帖子。数组“标记”是理想的结果。
var markers = [
    ['First Center','First Address',50,50],
    ['Second Center','Second Address', -25.363882,131.044922],
    ['Third Center','Third Address', 10.363882,95],
    ['Fourth Center','Fourth Address', -50,-90],
    ['Fifth Center','Fifth Address', 30,5],
];
window.markers = [
<?php while( have_rows('actin_center') ): the_row(); ?>
  ["<?php the_sub_field('center_name');?>","<?php the_sub_field('center_address'); ?>",<?php the_sub_field('latitude');?>, <?php the_sub_field('longitude');?>],
<?php endwhile; ?>
];
window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];