[英]how to create javascript object dynamically inside a function
我想在每次調用“dataObject”函數時動態創建一個 javascript 對象,所以我想做這樣的事情:
let dataObject = {};
function appendDiv() {
e = this.event.target;
//this id changes each time when the function is called
var current_id = e.id;
// here I had to initialized it because if I didn't, it would appear an error "TypeError: dataObject[(intermediate value)] is undefined"
dataObject[`${current_id}`] = {};
$('#creates').submit(function (event) {
var i, j;
for (i = 0; i < nbr_group.value; i++) {
inputlist = [];
for (j = 0; j < 3; j++) {
formChild = document.querySelectorAll('.period-select')[j].value;
inputlist[j] = formChild;
}
dataObject[`${current_id}`][`${i}`] = {
firstvalue: inputlist[0],
secondvalue: inputlist[1],
thirdvalue: inputlist[2]
}
}
});
}
所以問題是當第一次調用該函數時,子對象將被成功創建,但對該函數的第二次調用會將它們創建為空,例如:
// the first call:
dataObject = {
'1': {
'1': { '1': 'some values' },
'2': { '1': 'another value' }
}
};
//the second call or third or... :
dataObject = {
'1': {
'1': { '1': 'some values' },
'2': { '1': 'another value' }
},
'2': {}
};
如果你想復制一個對象,不要使用dataObject[`${current_id}`][`${i}`] = {firstvalue: inputlist[0], secondvalue: inputlist[1], thirdvalue: inputlist[2]};
,使用這個: let objectCopy = Object.assign({}, dataObject);
其中dataObject
是您要復制的對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.