函数中的filter()正在影响另一个

时间:2018-03-20 13:26:38

标签: javascript angular

在下面,我有一个应该过滤accountView的函数,但由于某种原因,它还会过滤accountCompare。不知道为什么会这样。我以为我已经分配了两个,所以accountCompare总是一个常数。

getAccount() {
    this.accounts.getAccount(this.accountId).subscribe(
        response => {
            this.accountView = this.apiHandler.responseHandler(response);
            this.accountCompare = this.apiHandler.responseHandler(response);
            console.log(this.accountCompare);
        },
        (err) => {
            this.apiHandler.errorHandler(err);
        }
    );
}

//then in this function, I filter accountView, however it appears to also be affecting accountCompare as well.

userDelete(id) {
    if (this.accountCompare.users.some(item => item.id === id)) {
        this.accountForm.value.usersToDelete.push(id);
    }
    this.accountView.users = this.accountView.users.filter(user => user.id !== id);
    /* this.accountForm.value.usersToAdd = this.accountForm.value.usersToAdd.filter(user => id !== id); */
    console.log(this.accountCompare);

}

1 个答案:

答案 0 :(得分:2)

非原始值通过引用传递。这意味着您实际上正在更新引用,而不是值。

快速破解你:

this.accountView = JSON.parse(JSON.stringify(this.apiHandler.responseHandler(response)));
this.accountCompare = JSON.parse(JSON.stringify(this.apiHandler.responseHandler(response)));