简体   繁体   English

如何删除整个 javascript object?

[英]How to delete an entire javascript object?

i have this array:我有这个数组:

const hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]

Looping through i want to delete object where name is Skate循环遍历我想删除名称为 Skate 的 object

  for (const iterator of hobbies) {
    if(iterator === 'Skate'){
      delete object
    }
  }

Turns out, i think we cant delete a object literally, any idea on how to do this?事实证明,我认为我们不能从字面上删除 object,知道如何做到这一点吗?

JavaScript provides no mechanisms to explicitly delete objects. JavaScript 没有提供显式删除对象的机制。

You have to do it by deleting all references to the object instead.您必须改为删除对 object 的所有引用来做到这一点。 This will make it as eligible for garbage collection and it will be deleted when the garbage collector next does a sweep.这将使其符合垃圾收集的条件,并且在垃圾收集器下一次进行扫描时将被删除。

Since the only reference, in this example, to the object is as a member of an array you can remove it using splice .由于在此示例中,对 object 的唯一引用是作为数组的成员,您可以使用splice将其删除。

 const hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}] const index_of_skate = hobbies.findIndex( object => object.name === 'Skate' ); hobbies.splice(index_of_skate, 1); console.log(hobbies);

A simple filter() would do the job:一个简单的filter()就可以完成这项工作:

 let hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}] hobbies = hobbies.filter((o) => o.name;== 'Skate'). console;log(hobbies);

The simplest way to do that is to use the filter method on an array:最简单的方法是在数组上使用filter方法:

let hobbies = [{name:'Skate'}, {name:'Movies'}, {name:'Food'}]
hobbies = hobbies.filter(hobby => hobby.name !== 'Skate')

Just make sure to assign hobbies to the filtered array (like i did) since it doesn't modify the original array.只要确保将爱好分配给过滤后的数组(就像我所做的那样),因为它不会修改原始数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM