[英]How to add new items to javascript array without over riding what is already inside the array
I have these 2 arrays declared
我声明了这两个数组
var newUnitsToGenerateObj = [];
var newUnitsToGenerate = {
UnitTypeID: null,
NumOfUnits: 0
};
in my UI I want the user to select the unitype and I want to pass it into thi newunitstogenerate then pass it into newunitstogenerateobj I thought this would be fairly simple like this 在我的UI中,我希望用户选择unitype,然后将其传递给newunitstogenerate,然后将其传递给newunitstogenerateobj,我认为这样会很简单
function AddUnitsToConfig() {
newUnitsToGenerate.UnitTypeID = $('#UnitTypeID').ejDropDownList('model.value');
newUnitsToGenerate.NumOfUnits = $('#NumOfUnits').val();
newUnitsToGenerateObj.push(newUnitsToGenerate);
console.log(newUnitsToGenerateObj);
}
so this function inserts the first value as expected when the button is clicked but if it is clicked a second time with new values this overrides what was in the array with the new data so I have a length of 2 as expected but they are the same values. 因此,此函数会在单击按钮时按预期插入第一个值,但如果第二次单击具有新值,则它将覆盖具有新数据的数组中的值,因此我的长度为预期的2,但它们相同价值观。 I want to build up the newunitstogenerateobj then pass it to the server.
我想建立newunitstogenerateobj,然后将其传递给服务器。
You're mutating newUnitsToGenerate
every time you call AddUnitsToConfig
. 你突变
newUnitsToGenerate
每次通话时间AddUnitsToConfig
。 You want to push a new object into the array with each call: 您希望通过每次调用将一个新对象推入数组:
function AddUnitsToConfig() {
newUnitsToGenerateObj.push({
UnitTypeID: $('#UnitTypeID').ejDropDownList('model.value');
NumOfUnits: $('#NumOfUnits').val();
});
console.log(newUnitsToGenerateObj);
}
Declare an empty json. 声明一个空的json。 inside the function
在函数内部
var newUnitsToGenerateObj = [];
function AddUnitsToConfig() {
var newUnitsToGenerate = {};
newUnitsToGenerate['UnitTypeID'] = $('#UnitTypeID').ejDropDownList('model.value');
newUnitsToGenerate['NumOfUnits'] = $('#NumOfUnits').val();
newUnitsToGenerateObj.push(newUnitsToGenerate);
console.log(newUnitsToGenerateObj);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.