简体   繁体   English

在索引处加入两个JavaScript数组

[英]Join two javascript arrays at index

I have this loop, the api returns markers fine, i want to add the url and the image inside the array. 我有这个循环,api返回的标记很好,我想在数组中添加url和图像。

let coordsList = [];

for (let i in markers) {
  let coords = markers[i].petLost.lostCoords;
  let url = petUrl + markers[i]._id;
  let image = petImage + markers[i].imageURL;
  coordsList.push(coords);
}

The result with this loop is: 该循环的结果是:

[ 24.728216, 36.2308272 ] , [ 27.728216, 33.2308272 ] , ...

How can i inject in there the url and the image for each corresponding item in the array? 我如何在其中为数组中的每个对应项注入url和图像?

Desired result: 所需结果:

[ 24.728216, 36.2308272, http://blabla.html, http://image.jpg ] , 
[ 27.728216, 33.2308272, http://blabla2.html, http://image2.jpg ]
 ...

You could just try this: 您可以尝试以下方法:

let coords = markers[i].petLost.lostCoords;
let url = petUrl + markers[i]._id;
coords.push(url)
let image = petImage + markers[i].imageURL;
coords.push(image);
coordsList.push(coords);

The above snippet can become more elegant as below: 上面的代码片段可以变得更加优雅,如下所示:

let markers = markers[i];
let markerData = markers.petLost
                        .lostCoords
                        .push(petUrl + markers._id) 
                        .push(petImage + markers.imageURL);
markersList.push(markerData);  

Note I did a rename, in order to make it more meaningful and readable. 注意我做了重命名,以使其更有意义和可读性。 If you follow this approach, you should replace the coordsList , wherever it is used with the markersList . 如果按照这个方法,你应该更换coordsList ,无论它是用来与markersList

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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