Very often there are times when we want to delete all elements of an array, as an option, we have a list of tasks, and we want to delete all tasks at the same time.
Consider the following list of elements:
let items = ["tea", "coffee", "milk"];
To remove all elements from an array, we set its value to an empty array
items = [];
This works fine, and you will find that this example is used constantly. But there is a problem with this ...
:
let items = ["tea", "coffee", "milk"];
let copy = items;
copy , copy items.
console.log(items);
console.log(copy);
.
, - , , , .
copy[2] = "oranges";
console.log(items);
console.log(copy);
items, , , :
items = [];
, items copy
console.log(items);
console.log(copy);
, items , copy .
, items = [], , copy.
, (array), (object), - , , , .
, , array = [], [] â , .
. obj = {name: 'David'}, obj , , .
let obj = { name: 'David' };
let newObj = obj;
console.log(obj);
console.log(newObj);
obj = null;
console.log(obj);
console.log(newObj);
:
- 0:
let items = ["tea", "coffee", "milk"];
let copy = items;
console.log(items);
console.log(copy);
items.length = 0;
console.log(items);
console.log(copy);
- splice :
let items = ["tea", "coffee", "milk"];
let copy = items;
console.log(items);
console.log(copy);
items.splice(0, items.length);
console.log(items);
console.log(copy);
, , , items = [];
:
We should not create additional links for an array or object, as this may lead to an undesirable result in the future. If you are sure that there are no references (* and will not appear) to the original array that we need to clear, then you can use array = [] to clear it, otherwise use either of the above two methods to clear the array.
Let's make the web better.