![](/img/trans.png)
[英]How to loop, concatenate and push content into an array in JavaScript
[英]how to push arrays in array and NOT concatenate?
我有以下 php 代码,它提供了一个名为“标记”的数组变量。
window.markers = [];
<?php if( have_rows('actin_center') ): ?>
<?php while( have_rows('actin_center') ): the_row(); ?>
window.markers.push( [ ['<?php the_sub_field('center_name'); ?>', '<?php the_sub_field('center_address'); ?>', <?php the_sub_field('latitude'); ?>, <?php the_sub_field('longitude'); ?>] ] );
<?php endwhile; ?>
<?php endif; ?>
到目前为止,这工作正常,但返回数组(处于警报状态)为:
Cool center 1,Rewitz Gofella, 1234 Lorem,50,50,Cool center 2,Lorem Ipsum, 1234 Quosque,60,60,Cool center 3,Veniat elaborat, 1234 Ipsum,70,70
然而,我需要的是以下形式,保留数组(子字段),因为它们最初位于数组内,而不是连接它们。 作为:
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],
];
正如您在上面的代码中看到的那样,我尝试使用简单的双括号 [[]] 但这不起作用。 如何正确地做到这一点? 非常感谢您的帮助。
PS:如果有人觉得有必要对我的问题投反对票,请告诉我为什么这样我可以学到一些东西。
由于评论:
alert( [[1,2][3,4]] )
会弹出错误的1,2,3,4
alert( JSON.stringify([[1,2][3,4]])
会弹出[[1,2],[3,4]]
.push([1,2])
将添加一个数组到markers
: [[1,2],[3,4],[5,6]]
.push(1,2)
将元素添加到markers
: [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; ?>
];
结果应该是这样的
window.markers = [
['First Center', 'First Address', 50, 50],
['Second Center','Second Address',-25.363882, 131.044922],
[... ,... , ... ,...],
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.