【发布时间】:2014-10-25 17:15:45
【问题描述】:
我尝试复制一个对象数组,但失败了。每次我最终都会得到一组对原始 aray 的引用。
我尝试了“.concat()”,我使用“for”分别复制每个元素,但是每次我在临时数组中进行更改时,原始数组也发生了变化。
这是代码。
Glossary:
tablicaZnacznikow - original array
placeholder - temporary array
tempClosest - id of closest marker
startingPointID - id of marker from witch i start calculation
.meta field - defines if marker has been added to polyline
var placeholder = tablicaZnacznikow.concat();
var tempArrayOfSomething = [placeholder[startingPointID].latLng];
for (var i = 0; i < placeholder.length; i++) {
var tempClosest = findClosestMarkerToAnotherMarker(placeholder, startingPointID);
tempArrayOfSomething.push(placeholder[tempClosest].latLng);
startingPointID = tempClosest;
placeholder[tempClosest].meta = "USED";
console.log(tempClosest);
}
我使用此代码创建一个数组,为 gMap3 折线创建路径。 提前致谢。
【问题讨论】:
-
如果您将一个对象分配给另一个变量,您不会克隆该对象,相反,两个变量将包含对内存中相同数据的相同引用。因此,您必须克隆对象。见stackoverflow.com/q/122102/1529630 和stackoverflow.com/q/728360/1529630
标签: javascript arrays javascript-objects jquery-gmap3