JavaScript中的对象删除

395

我对JavaScript的delete操作符感到有些困惑。看下面这段代码:

var obj = {
    helloText: "Hello World!"
};

var foo = obj;

delete obj;
执行完这段代码后,objnull,但是foo仍然引用着一个和obj完全一样的对象。我猜测这个对象就是foo指向的那个对象。
这让我感到困惑,因为我本来希望使用delete obj语句可以从内存中删除obj所指向的对象,而不仅仅是删除变量obj本身。
这是因为JavaScript的垃圾回收器是基于保留/释放机制工作的,所以如果没有其他变量指向这个对象的话,它将会被从内存中删除。
(顺便说一下,我的测试是在Safari 4上进行的。)

8
以下是翻译的结果:供您参考。 https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator - Daniel A. White
3
以上链接应更改为:http://perfectionkills.com/understanding-delete。 - johnmdonahue
1
@Steve Harrison,delete 在 JavaScript 中不是删除一个对象的操作,而是删除一个对象的键。在您的情况下,应该使用 remove 操作。var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;注意:对象并没有被删除,请检查 obj。 正确的用法是:delete obj.helloText 然后再检查 foo,此时 foo 就变成了一个空对象。 - Umair Ahmed
2
@UmairAhmed,自由翻译:delete`在Javascript中并不是用于删除对象的。`delete`用于移除对象的键。在您的情况下 `var obj = { helloText: "Hello World!" }; var foo = obj; delete obj;`, 对象并没有被删除。请检查`obj`。然后运行`delete obj.helloText`,您会看到`foo`现在指向一个空对象。 - Pacerier
可能会对您有所帮助:如果您正在使用Object.defineProperty()/Object.defineProperties()定义属性,任何未显式设置为configurable: true的属性都无法被删除。嘿,我曾经为此苦恼了一段时间。 - Phil Tune
14个回答

0

这对我来说可行,虽然这不是一个好的做法。它只是删除了对象所属的所有相关元素。

 for (element in homeService) {
          delete homeService[element];
  }

什么是最佳实践?我记得阅读过删除操作符不是删除对象属性的最佳实践。我相信我在Crockford的JavaScript书中读到了这一点,但目前无法找到它。 - zero_cool

0

删除运算符可以删除对象、对象的属性或数组中的元素。该运算符还可以删除未使用 var 语句声明的变量。 在下面的示例中,'fruits' 是一个声明为 var 的数组,并被删除了(真的吗?)

delete objectName
delete objectName.property
delete objectName[index] 
delete property // The command acts  only within a with statement.

var fruits = new Array("Orange", "Apple", "Banana", "Chery");
var newParagraph = document.createElement("p"); 
var newText = document.createTextNode("Fruits List : " + fruits);
newParagraph.appendChild(newText);
document.body.appendChild(newParagraph);
//Delete the array object.
delete fruits;
var newParagraph1 = document.createElement("p");
var newText1 = document.createTextNode("Display the Fruits after delete the array object - Fruits List : "+ fruits;); 
newParagraph1.appendChild(newText1);
document.body.appendChild(newParagraph1);

https://www.w3resource.com/javascript/operators/delete.php


0

我们有多种方法来删除对象属性。

箭头函数:我们还可以使用箭头函数从对象中删除属性,这是一种简单的一行解决方案。

const obj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

const fn = (key, { [key]: deletedKey, ...others }) => others;

console.log(fn('first', obj))        // { 'second': 'two', 'third': 'three' }
Reduce方法:我们可以使用reduce方法在JavaScript中从原始对象中删除特定属性。
const obj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

const exceptSecond = Object.keys(obj).reduce((acc, key) => {
    if (key !== 'second') {
        acc[key] = obj[key]
    }
    return acc
}, {})

console.log(exceptSecond)    // { 'first': 'one', 'third': 'three' }

删除:这是简单易行的删除方式。

delete obj.first; 
// Or
delete obj['first'];

使用 "loadash" 库中的 unset、omit、pick 方法:

    import { unset } from 'lodash'


const obj = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

unset(obj, 'third')        // true

console.log(obj)        // { 'first': 'one', 'second': 'two' }

// Using omit 
import { omit } from 'lodash'
const obj1 = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

omit(obj1, [ 'first', 'second' ])

console.log(obj1)  

反射删除属性: 这是ES6中引入的新内置对象。现在可以通过从该反射对象调用已删除属性()函数来删除对象属性。

此函数相当于我们在第一种方法中使用的delete运算符。

const someObject = {
    'first': 'one',
    'second': 'two',
    'third': 'three'
}

Reflect.deleteProperty(someObject, 'second')

console.log(someObject)        //  { 'first': 'one', 'third': 'three' }

0
如果您想根据对象的值来删除它,请执行以下操作:
Object.keys(obj).forEach((key) => {
  if (obj[key] === "Hello World!") {
    delete obj[key];
  }
});

但是删除一个对象并不是一个好主意。所以,将其设置为undefined,这样当您将其传递给参数时,它就不会显示出来。无需删除。

Object.keys(obj).forEach((key) => {
  if (obj[key] === "Hello World!") {
    obj[key] = undefined;
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接