通过for循环向数组中添加元素,结果全部相同的问题?
//标记点模板
const vmarker = {
id: 0,
latitude: 0,
longitude: 0,
iconPath: '?',
height: "30px",
width: "30px",
callout: {
borderWidth: 0,
borderColor: "#00b26a",
color: "#00b26a",
padding: 6,
borderRadius: 3,
display: "ALWAYS",
content: "?",
textAlign: "center",
anchorY: -5
}
}
/**
* 构造标记点数据
* [@param](/user/param) {*} data是服务器返回的数据
*/
function buildMarkers(data) {
let markers = new Array([data.length])
for (let e in data) {
let marker = vmarker
marker.id = parseInt(data[e].id)
let arr = data[e].lonlat.split(',')
marker.latitude = arr[0]
marker.longitude = arr[1]
marker.iconPath = data[e].users.avatar
marker.callout.content = data[e].users.username
console.log(marker)
// markers.push(marker)
// markers[e]=marker
markers.splice(e,1,marker)
}
console.log(markers)
return markers
}
for循环里面打印的数据都是正确的,但无论是通过push还是splice、或直接赋值,最后在循环外得到的结果全部一样,且都是最后一次循环得到的数据
这是循环中的:
这是循环外的:
1 回复
这个是JavaScript object 引用值的问题。
作为模版的话,push用,cloneDeep()(深拷贝)
const vmarker = {
id: 0,
latitude: 0,
longitude: 0,
iconPath: '?',
height: "30px",
width: "30px",
callout: {
borderWidth: 0,
borderColor: "#00b26a",
color: "#00b26a",
padding: 6,
borderRadius: 3,
display: "ALWAYS",
content: "?",
textAlign: "center",
anchorY: -5
}
}
const arr = []
arr.push(cloneDeep(vmarker))
cloneDeep实现网上有很多,思路是DFS遍历object,注意边界判断。