分配给变量切片数组允许修改原始数组
Assigning to variable sliced array allows modify original array
我们有一个 class,它有一个私有数组。
class BookService{
private booksList: Book[];
constructor (){
this.booksList = [
new Book('Tales', true),
new Book('Novels', false),
new Book('Dictionary', false)
];
}
getBooks(){
return this.booksList;
}
}
class Book{
constructor ( public name: string, public isRead: boolean ){}
}
export const bookService = new BookService();
我们也有一个实现。
import {bookService} from './book-service';
//get copy of original array which is not by reference
let books: any = bookService.getBooks().slice(0);
//log local array
console.log(books);
// modify local array
books[1].isRead = true;
//log original array
console.log(bookService.getBooks());
我们得到了原始数组的副本。然后我们修改了本地数组(原始数组的副本)。我们得到了修改后的原始数组。
我不明白为什么原始私有数组被修改了?
如果我修改getBooks为
getBooks(){
return this.booksList.slice(0);
}
没用。
如果我使用 lodash 方法修改 getBooks _.cloneDeep Method description
getBooks(){
return _.cloneDeep(this.booksList);
}
原数组不会被修改。
为什么?如何避免与此类情况相关的错误?
当您用 slice
克隆数组时,里面的对象保持不变。
如果数组 arr
中有三个对象 a
、b
和 c
,并且克隆它,新数组仍将包含对 a
、b
和 c
,而不是看起来相同的新对象。
var arr = [ a, b, c ];
var arr2 = arr.slice(0); // [ a, b, c ];
arr === arr2; // false - they are not the same array
arr[0] === arr2[0]; // true - they contain the same a object
这意味着如果您从 arr2
获得 a
,它与 arr
中的相同 a
对象 - 因此修改其中一个会同时修改两个。
我们有一个 class,它有一个私有数组。
class BookService{
private booksList: Book[];
constructor (){
this.booksList = [
new Book('Tales', true),
new Book('Novels', false),
new Book('Dictionary', false)
];
}
getBooks(){
return this.booksList;
}
}
class Book{
constructor ( public name: string, public isRead: boolean ){}
}
export const bookService = new BookService();
我们也有一个实现。
import {bookService} from './book-service';
//get copy of original array which is not by reference
let books: any = bookService.getBooks().slice(0);
//log local array
console.log(books);
// modify local array
books[1].isRead = true;
//log original array
console.log(bookService.getBooks());
我们得到了原始数组的副本。然后我们修改了本地数组(原始数组的副本)。我们得到了修改后的原始数组。
我不明白为什么原始私有数组被修改了?
如果我修改getBooks为
getBooks(){
return this.booksList.slice(0);
}
没用。
如果我使用 lodash 方法修改 getBooks _.cloneDeep Method description
getBooks(){
return _.cloneDeep(this.booksList);
}
原数组不会被修改。 为什么?如何避免与此类情况相关的错误?
当您用 slice
克隆数组时,里面的对象保持不变。
如果数组 arr
中有三个对象 a
、b
和 c
,并且克隆它,新数组仍将包含对 a
、b
和 c
,而不是看起来相同的新对象。
var arr = [ a, b, c ];
var arr2 = arr.slice(0); // [ a, b, c ];
arr === arr2; // false - they are not the same array
arr[0] === arr2[0]; // true - they contain the same a object
这意味着如果您从 arr2
获得 a
,它与 arr
中的相同 a
对象 - 因此修改其中一个会同时修改两个。