我在两个数组中复制数据this.contactOptions和this.updatedContactOptions,但是当我修改this.contactOptions时它也修改了this.updatedContactOptions,请帮助我理解为什么它在其他数组中进行更改,即使我是没有更新它?
这是组件文件
export class JobListComponent implements OnInit {
private contactOptions: Array<any> = [];
private updatedContactOptions: Array<any> = [];
private jobFormData: any = {
"contactDetails": [],
};
private jobFormDataOriginal: any;
private jobDTOptions: any = {};
private isUnknownError: boolean = false;
private errorHtml: string;
constructor(private elementRef: ElementRef, private utility: Utility) {
this.jobForm = this.formBuilder.group({
'contactDetails': [],
'tags': [],
'dispatchJob': true
});
}
ngOnInit(): void {
let self = this;
this.getWorkflow();
this.getContacts();
}
clone(object: any) {
return JSON.parse(JSON.stringify(object));
}
setFormData(data,contactOptions) {
let self = this;
if (!data['endLocation']) {
data['endLocation'] = {
"address": '',
"latitude": '',
"longitude": ''
}
}
this.jobFormData = this.clone(data);
if (data.workflow) {
this.jobFormData.workflowId = data.workflow.id;
}
if (data.assignee) {
this.jobFormData.assigneeId = data.assignee && data.assignee.userId ? data.assignee.userId : null;
this.jobForm.get('assignee.user').setValue('user');
this.assigneeType = 'user';
}
this.jobFormData.contactDetails = [];
if (data.contacts != null) {
var isDel=[];
for (let j = 0; j < data.contacts.length; j++) {
if(data.contacts[j].deleted){
isDel.push({
value: data.contacts[j].id,
label: data.contacts[j].firstName + " " + data.contacts[j].lastName,
disabled:data.contacts[j].deleted
});
}
if(isDel.length>0){
this.contactOptions[this.contactOptions.length]=this.clone(isDel[0]);
}
this.jobFormData.contactDetails=[...data.contacts[j].id];
//this.jobFormData.contactDetails = [...this.jobFormData.contactDetails];
}
}
this.jobFormData.tags = [];
if (data.contacts != null) {
for (let i = 0; i < data.tags.length; i++) {
this.jobFormData.tags[i] = data.tags[i].tagId;
}
this.jobFormData.startDateTimeInDate = moment(data.scheduledStartTime).tz(self.timeZone).format(this.utility.DATEFORMAT_CALENDER[self.dateTimeFormat]);
this.jobFormData.endDateTimeInDate = moment(data.estimatedEndTime).tz(self.timeZone).format(this.utility.DATEFORMAT_CALENDER[self.dateTimeFormat]);
}
}
getContacts() {
// this.contactService.getContacts().subscribe(
// data => {
let result = [{"id":"99F224517781461CB44DDE9DB298367E","firstName":"a","lastName":"a","companyName":"","address":"","email":"a@g.com","primaryContactNumber":"9898989898","altContactNumber":null,"websiteURL":"","deleted":false},{"id":"9780ACC7746A4CAC8A013914CC9FF518","firstName":"as","lastName":"frwef","companyName":"tr","address":"","email":"df@ds.cde","primaryContactNumber":"fwwdqf","altContactNumber":null,"websiteURL":"","deleted":false},{"id":"DCEB2AC83F374A1B89C631A7FF5BE543","firstName":" te","lastName":"te","companyName":"","address":"","email":"rte@ef.dfg","primaryContactNumber":"rt","altContactNumber":null,"websiteURL":"","deleted":false},{"id":"72DD16997D0242E99F0A90A0080D270B","firstName":"William","lastName":"Howell","companyName":"Fleet Solutions","address":"Sugarloaf Township Pennsylvania USA ","email":"william_howell@gmail.com","primaryContactNumber":"+1-87511222556","altContactNumber":"","websiteURL":"www.fleet-solutions.com","deleted":false},{"id":"78292688C0914D149693CB696FF1AEB1","firstName":"William","lastName":"Howell","companyName":"Fleet Solutions","address":"Sugarloaf Township Pennsylvania USA ","email":"william_howell@gmail.com","primaryContactNumber":"+1-87511222558","altContactNumber":"","websiteURL":"www.fleet-solutions.com","deleted":false},{"id":"DF0E93140DAA4E53A5BB9A9002E72544","firstName":"William","lastName":"Howell","companyName":"Fleet Solutions","address":"Sugarloaf Township Pennsylvania USA ","email":"william_howell@gmail.com","primaryContactNumber":"+1-87511222557","altContactNumber":"","websiteURL":"www.fleet-solutions.com","deleted":false},{"id":"F661702AF20E4F12ACED51A9F489CC3C","firstName":"William","lastName":"Howell","companyName":"Fleet Solutions","address":"Sugarloaf Township Pennsylvania USA ","email":"william_howell@gmail.com","primaryContactNumber":"+1-87511222555","altContactNumber":"","websiteURL":"www.fleet-solutions.com","deleted":false}]; //data.data.contacts;
for (let i = 0; i < result.length; i++) {
this.contactOptions.push({
value: result[i].id,
label: result[i].firstName + " " + result[i].lastName,
disabled: result[i].deleted
});
this.updatedContactOptions.push({
value: result[i].id,
label: result[i].firstName + " " + result[i].lastName,
disabled: result[i].deleted
});
}
// },
// (err) => {
// this.logError(err);
// });
}
clearJobForm() {
let self = this;
let format = this.utility.DATEFORMAT_CALENDER[self.dateTimeFormat];
this.jobFormSubmitted = false;
this.validAddress = true;
this.jobForm.get('assignee.user').setValue('user');
this.assigneeType = 'user';
this.jobFormData = this.clone(this.jobFormDataOriginal);
this.initDateTimePicker();
}
toggleJobForm(rowData: any, isEdit: boolean) {
let self = this;
this.initDateTimePicker();
this.updatedContactOptions=this.contactOptions;
for(let g=0;g<this.contactOptions.length;g++){
if(this.updatedContactOptions[g].disabled){
this.updatedContactOptions.splice(g,1);
}
}
this.contactOptions=this.updatedContactOptions;
if (isEdit) {
this.jobEditId = rowData.id;
jQuery("span.deletejob:not('.inactive')").removeClass("disabled");
jQuery('#' + rowData.id).find('span.deletejob').addClass('disabled');
this.validAddress = true;
this.jobFrmVisible = true;
this.setFormData(rowData,this.contactOptions);
this.jobSubmitButton = this.jobsButtons['UPDATE_JOB'];
this.jobFrmBtnTitle = this.jobsButtons['CANCEL'];;
} else {
if (this.jobFrmVisible) {
if (this.jobEditId) {
jQuery('#' + this.jobEditId).find("span.deletejob:not('.inactive')").removeClass('disabled');
}
this.jobEditId = '';
this.jobFrmVisible = false;
this.jobFrmBtnTitle = this.jobsButtons['CREATE_JOB'];
this.jobSubmitButton = this.jobsButtons['CREATE_JOB'];
this.clearJobForm();
} else {
this.jobFrmVisible = true;
this.jobSubmitButton = this.jobsButtons['CREATE_JOB'];;
this.jobEditId = '';
this.jobFrmBtnTitle = this.jobsButtons['CANCEL'];;
}
}
}
logError(error: any) {
console.log(error);
}
handleJobErrors(err: any) {
let self = this;
self.errorHtml = '';
for (let error of err) {
switch (error.code) {
case "1032":
self.jobForm.controls['number'].setErrors({
"duplicateJobNumber": true
});
break;
default:
self.isUnknownError = true;
self.errorHtml += error.message + '</br>';
}
};
if (self.isUnknownError == true) {
self.jobOperation = "ERROR";
jQuery('#jobModal').modal('show');
jQuery('div#jobModal .modal-body').empty().append(self.errorHtml);
}
}
}
为什么其他数组会更新?
答案 0 :(得分:2)
如果要复制数组,请使用Object.assign()方法,如 -
let arr1 = [1,2,3];
let arr2;
Object.assign(arr2, arr1);
如果您将其指定为 -
arr2 = arr1;
然后当你在一个数组中更改某些内容时,两个数组都会更新 因为它的参考。
如果要保留一个原始副本,请使用const
const arr2 = arr1; // you can use arr2(it cannot be change)
答案 1 :(得分:0)
也许我的意图不对,但这是你的toggleJobForm() - 方法
toggleJobForm(rowData: any, isEdit: boolean) {
let self = this;
this.initDateTimePicker();
将this.contactOptions复制到this.updatedContactOptions
this.updatedContactOptions=this.contactOptions;
然后你修改this.updatedContactOptions
for(let g=0;g<this.contactOptions.length;g++){
if(this.updatedContactOptions[g].disabled){
this.updatedContactOptions.splice(g,1);
}
}
然后将其复制回this.contactOptions
this.contactOptions=this.updatedContactOptions;
在这种方法中,它清楚地表明,每当你更改this.updatedContactOptions时,也会改变this.ContactOptions。
或者您是否故意这样做?