Warum löschen Sie nicht alle Elemente des Arrays, indem Sie es [] neu zuweisen?


Sehr oft gibt es Zeiten, in denen wir alle Elemente eines Arrays löschen möchten. Optional haben wir eine Liste von Aufgaben und möchten alle Aufgaben gleichzeitig löschen.


Betrachten Sie die folgende Liste von Elementen:


let items = ["tea", "coffee", "milk"];

Um alle Elemente aus einem Array zu entfernen, setzen wir seinen Wert auf ein leeres Array


items = [];

Dies funktioniert einwandfrei und Sie werden feststellen, dass dieses Beispiel ständig verwendet wird. Aber es gibt ein Problem damit ...



:


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 = [];


:


Wir sollten keine zusätzlichen Links für ein Array oder Objekt erstellen, da dies in Zukunft zu einem unerwünschten Ergebnis führen kann. Wenn Sie sicher sind, dass es keine Verweise auf das ursprüngliche Array gibt (* und nicht angezeigt wird), die gelöscht werden müssen, können Sie es mit array = [] löschen. Andernfalls können Sie das Array mit einer der beiden oben genannten Methoden löschen.


Lassen Sie uns das Web verbessern.

All Articles