【发布时间】:2017-11-05 10:00:31
【问题描述】:
我正在尝试使用 JSON 对象作为 JSON 对象数组中新默认值的来源。在我的第一次尝试中,我这样做了:
var records=
[{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
{"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"}]
var defaultRecord =
{"Key1":"DefaultValue1","Key2":"DefaultValue2","Key3":"DefaultValue3"}
pushNewDefaultRecord()
pushNewDefaultRecord()
changeFirstDefaultRecord("NEW VALUE")
showRecord()
function pushNewDefaultRecord(){
records.push(defaultRecord)
}
function changeFirstDefaultRecord(newValue){
records[2].Key1 = newValue
records[2].Key2 = newValue
records[2].Key3 = newValue
}
function showRecord(){
console.log(JSON.stringify(records))
}
这会产生以下数组:
[{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
{"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"}]
我意识到推送到记录数组的不是 defaultRecord 对象中的数据,而是对象本身,因此当我更新一条记录时,两条新记录都反映了更改。
将 pushNewDefaultRecord 函数更改为使用 JSON.stringify 然后 JSON.parse 有效,但看起来非常尴尬。有没有更清洁的方法来解决这个问题?
function pushNewDefaultRecord(){
var newDefaultRecord = JSON.parse(JSON.stringify(defaultRecord))
records.push(newDefaultRecord)
}
生产:
[{"Key1":"ValueA","Key2":"ValueA","Key3":"ValueA"},
{"Key1":"ValueB","Key2":"ValueB","Key3":"ValueB"},
{"Key1":"NEW VALUE","Key2":"NEW VALUE","Key3":"NEW VALUE"},
{"Key1":"DefaultValue1","Key2":"DefaultValue2","Key3":"DefaultValue3"}]
【问题讨论】:
-
那么,您的问题是什么?
-
可以使用一个函数,每次需要时返回一个新的默认对象
-
我想你已经这样做了,第二个
pushNewDefaultRecord会在你每次调用它时创建一个新的默认对象。
标签: javascript arrays json