要合并的枚举对象
const marker = {
id: 1,
iconPath: img,
width: 50,
height: 50,
joinCluster: true, // 指定了该参数才会参与聚合
label: {
width: 50,
height: 30,
borderWidth: 1,
borderRadius: 10,
bgColor: '#ffffff'
}
};
const positions = [{
latitude: 35.040266,
longitude: 118.351174,
}, {
latitude: 35.05151,
longitude: 118.34787,
}, {
latitude: 35.042009,
longitude: 118.356077,
}, {
latitude: 35.037898,
longitude: 118.350418,
}]
实现的代码
const markers = []
positions.forEach((p, i) => {
const newMarker = Object.assign({
}, marker, p)
newMarker.id = i + 1
newMarker.label.content = i + 1
markers.push(newMarker)
})
打印markers的返回结果却跟预想的不同 相同的key值 id是深拷贝 label.content是浅拷贝
修改代码为
const markers = []
positions.forEach((p, i) => {
const newMarker = Object.assign({
}, marker, p)
newMarker.id = i + 1
newMarker.label.content = `label ${
i + 1}`
var newMarkers = JSON.parse(JSON.stringify(newMarker))
markers.push(newMarkers)
})
这样写就可以了
总结:Object.assign 合并对象时 第一层为深拷贝 第二层为浅拷贝 浅拷贝的newMarker.label.content可以理解为引用的marker.label.content
marker.label.content改变所有的newMarker.label.content跟着改变 所以我们得到了4个content: 4 在push储存之前深拷贝一下newMarker就可以了