-1
我想2個屬性添加到根據某些條件的對象: 例如:添加多個屬性的對象只顯示最後創建的道具
var data= [
{ name:"Jan", score:4, scale:4 },
{ name:"Feb",score:8, scale:3 },
{ name: "Mar", score:2, scale:9 },
{ name: "Apr", score:10, scale:1 }
]
data.map(function(point) {
if (some condition) {
point.m = {
a: 2
}
}else {
point.m = {
a: 10
}
}
})
//so result in the data im expecting to add the prop `m` of type object to the array.
data = [
{ name:"Jan", score:4, scale:4,m:{a:2} },
{ name:"Feb",score:8, scale:3,m:{a:2} },
{ name: "Mar", score:2, scale:9,m:{a:10} },
{ name: "Apr", score:10, scale:1,m:{a:2} }
]
現在不同的比例我想補充另一場來支撐m
,即時通訊做:
point.m = {
b: 10 // this value is dynamic so could change.
}
,所以我很期待:
data = [
{ name:"Jan", score:4, scale:4,m:{a:2, b:10} },
{ name:"Feb",score:8, scale:3,m:{a:2, b:10} },
{ name: "Mar", score:2, scale:9,m:{a:10, b:10} },
{ name: "Apr", score:10, scale:1,m:{a:2, b:10} }
]
但由於某些原因,只需將最後一個字段添加到道具中。我得到的結果如下:
data = [
{ name:"Jan", score:4, scale:4,m:{ b:10} },
{ name:"Feb",score:8, scale:3,m:{ b:10} },
{ name: "Mar", score:2, scale:9,m:{ b:10} },
{ name: "Apr", score:10, scale:1,m:{b:10} }
]
我在這裏錯過了什麼?
嘗試使用'point.m.b = 10'這樣做會再次初始化'point.m',從而得到結果。 – Manish
打開你的調試器,在'point.m = {b:10}'這一行放置一個斷點。當你到達那裏時,檢查'point.m'。然後,在賦值語句之後,再次檢查'point.m'。然後認真思考。 – 2017-06-01 02:57:44