Why not delete all elements of the array by reassigning it to []?


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); // ["tea", "coffee", "milk"]
console.log(copy); // ["tea", "coffee", "milk"]

.


, - , , , .


copy[2] = "oranges";
console.log(items); // ["tea", "coffee", "oranges"]
console.log(copy); // ["tea", "coffee", "oranges"]

items, , , :


items = [];

, items copy


console.log(items); // []
console.log(copy); // ["tea", "coffee", "oranges"]

, items , copy .


, items = [], , copy.


, (array), (object), - , , , .


, , array = [], [] — , .


. obj = {name: 'David'}, obj , , .


let obj = { name: 'David' };
let newObj = obj;
console.log(obj); // { name: 'David' }
console.log(newObj); // { name: 'David' }
obj = null;
console.log(obj); // null
console.log(newObj); // { name: 'David' }

:


  1. 0:
    let items = ["tea", "coffee", "milk"];
    let copy = items;
    console.log(items); // ["tea", "coffee", "milk"]
    console.log(copy); // ["tea", "coffee", "milk"]
    items.length = 0;
    console.log(items); // []
    console.log(copy); // []
  2. splice :
    let items = ["tea", "coffee", "milk"];
    let copy = items;
    console.log(items); // ["tea", "coffee", "milk"]
    console.log(copy); // ["tea", "coffee", "milk"]
    //   ,    0     
    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.

All Articles