لماذا لا تحذف جميع عناصر المصفوفة بإعادة تعيينها إلى []؟


غالبًا ما تكون هناك أوقات نريد فيها حذف جميع عناصر المصفوفة ، كخيار ، لدينا قائمة بالمهام ، ونريد حذف جميع المهام في نفس الوقت.


خذ بعين الاعتبار قائمة العناصر التالية:


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

لإزالة جميع العناصر من مصفوفة ، نقوم بتعيين قيمتها على مصفوفة فارغة


items = [];

هذا يعمل بشكل جيد ، وسوف تجد أن هذا المثال يستخدم باستمرار. ولكن هناك مشكلة في هذا ...



:


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


:


لا ينبغي لنا إنشاء روابط إضافية لصفيف أو كائن ، لأن هذا قد يؤدي إلى نتيجة غير مرغوب فيها في المستقبل. إذا كنت متأكدًا من عدم وجود مراجع (* ولن تظهر) إلى الصفيف الأصلي الذي نحتاج إلى مسحه ، فيمكنك استخدام الصفيف = [] لمسحه ، وإلا استخدم أيًا من الطريقتين أعلاه لمسح الصفيف.


دعونا نجعل الويب أفضل.

All Articles