Home  >  Article  >  Web Front-end  >  How to delete attributes in object in javascript

How to delete attributes in object in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-09 15:24:0924403browse

In js, you can use the delete keyword to delete attributes in object, and the syntax format is "delete object.attribute". The delete operator is used to delete an attribute of an object. When the delete operator returns true, it means it can be deleted, and when it returns false, it means it cannot be deleted.

How to delete attributes in object in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

The semantically correct way to delete an attribute from an object is to use the delete keyword.

Given object

const car = {
  color: 'blue',
  brand: 'Ford'
}

You can remove properties from this object using the following command

delete car.brand

How to delete attributes in object in javascript

The way it works is also Represented as:

delete car['brand']
delete car.brand
delete newCar['brand']

Set the property to undefined

If you need to do this in a very optimized way, such as when operating on a large number of objects in a loop, another The choice is to set the property to undefined.

Due to its nature, the performance of delete is much slower than simply reassigning to undefined , up to 50 times slower.

However, keep in mind that the property is not removed from the object. Its value is erased, but if you iterate over the object it still exists:

Using delete is still very fast, you should only look into this kind of performance if you have a good reason to do so problem, otherwise having clearer semantics and functionality is always preferred.

Delete attributes without changing the object

Extended information:

The delete operator is used to delete an attribute of the object.

Syntax:

Use the delete operator directly

delete object.property 或 delete object['property']

For example:

var person = {
    name: 'abc'
    age: 18
}

delete person.name

console.log(person) // {age: 18}

Return value:

The delete operator has a return value , the return value is a Boolean value, which is true in all cases. Even if you delete a non-existent attribute, it will return true. It is still the same code as above. Why not print the return value and see

console.log(delete person.name) //true
console.log(delete person.job) //即使删除对象不存在的属性依然返回true

But there are exceptions. (returns false), if the property is a non-configurable property (for the concept of non-configurable properties, you can refer to Object.defineProperty, I was a little confused when I first heard about this concept), in non-strict mode, returns false, In strict mode, a syntax error exception will be thrown.

Specific use

1. The object attribute does not exist

As mentioned above, if you delete an attribute that does not exist in the object, delete is invalid, but the return value is still true

2. The property with the same name exists on the prototype chain

If the delete operator successfully deletes the property, the property will never exist. However, if the property with the same name exists on the prototype chain of the object, the object will be deleted from the prototype chain. The property with the same name is inherited on the prototype chain. But it has nothing to do with memory. Memory management is not something that the delete operator can operate, and it has nothing to do with it. Memory management recommends this MDN article

// 构造函数
function Person() {
    this.name = "张三",
    this.job = "工程师"
}

Person.prototype.name = "李四"
// 创建实例对象
var p = new Person();
// 只删除p实例的name属性
delete p.name;
console.log(p) => // 通过打印如下图,name属性成功删除
接下来看: 
console.log(p.name) => // '李四' 依然可以访问到

So it can be seen that the delete operation will only work on its own attributes. Here you can console 'Zhang San', which is the reason for the scope chain. When the instance itself has no When this attribute is found, it will look for whether its prototype has the attribute with the same name.

3. Use var declaration

Attributes (including functions) declared using var cannot be deleted from the global scope or function scope

Declared in the global scope Attributes:

// 声明属性
var a = 1; // 等同于window.a
delete a  // 严格模式下抛出语法异常 SyntaxError
console.log(a); // 1 非严格模式下
console.log(delete a); // 非严格模式下false
// 声明函数
var fn = function () {
    console.log(1);
}
delete fn // 严格模式下抛出语法异常  SyntaxError
fn() // 1 非严格模式下delete失效, 函数依然存在

// 另外, 除字面量定义外,匿名函数定义函数效果也是一样

Declaring attributes in the function scope (the effect is the same as in the global scope):

// 局部作用域声明属性
funtion fn() {
    var a = 1;
    delete a; // 严格模式下抛出语法异常 SyntaxError
    console.log(a); // 1
    console.log(delete a); // 非严格模式下false
}

fn();
// 局部作用域声明函数
var fn = function() {
    var fn2 = function() {
        console.log(1);
    };
    delete fn2 // 严格模式下抛出语法异常 SyntaxError 
    console.log(delete fn2); // false 非严格模式下
    fn2(); // 1
}
fn();

In addition, it should be noted that functions defined in the object can be deleted , the same as attributes, such as

var person = {
    name: '张三',
    showName: function () {
        console.log(this.name);
    }
}
delete person.showName
console.log(person.showName) // undefined

4. Attributes declared with let and const

Any attribute declared with let or const cannot be deleted from the scope in which it is declared. I tried The effect is the same as that of var. Currently I can only understand this. If you know the master, please give me some advice

5. Unsetable attributes

Math, Array, Object, etc. are built-in The properties of objects cannot be deleted

console.log(Array.length); // 1
delete Array.length
console.log(Array.from); 0
delete Array.prototype //严格模式下抛出异常
console.log(Array.prototype) // 非严格模式下,prototype依然存在, 可以自己试试了,自己动手,丰衣足食
console.log(Array.prototype.join); // 非严格模式下,join方法依然存在

It should be noted that only the properties of these built-in objects cannot be deleted, and the methods of built-in objects can be deleted, such as:

console.log(Array.forEach); // 内置函数
delete Array.forEach // 不用区分严格模式与否
console.log(Array.forEach); // undefined

Object.defineProperty() setting It is an unsettable property and cannot be deleted

var person = {};
Object.defineProperty(person, 'name', {
    value: '张三',
    configurable: false
})
delete person.name // 严格模式下,抛出异常
console.log(person.name); // 张三
console.log(delete person.name); // 非严格模式false

The unsettable property created by var, let and const cannot be deleted by the delete operation

var a = 'abc'; // 属于window 等同于window.a
var aVal = Object.getOwnPropertyDescriptor(window, 'a'); 
console.log(aVal);
//  aVal输入如下   
//    {
//       value: 2,
//         writable: true, 
//         enumerable: true, 
//         configurable: false // 由于是var声明的属性,所以为false
//     }
var a = 'abc'; // 属于window 等同于window.a
delete a // 严格模式下抛出异常
var aVal = Object.getOwnPropertyDescriptor(window, 'a'); 
console.log(aVal);
console.log(delete a); //false
//  非严格模式下,aVal输入如下   
//    {
//       value: 2,
//         writable: true, 
//         enumerable: true, 
//         configurable: false // 由于是var声明的属性,所以为false
//     }

If you haven’t read it at first, let’s take a look at Object. defineProperty. If you understand, you can skip it directly.

6. Delete an array

When you use the delete operator to delete an element of an array, the deleted element will be deleted from the array, but the length of the array will not change

var arr = [1, 2, 3];
delete arr[1]
console.log(arr); // [1, undefined × 1, 2]
console.log(delete arr[1]) // true
console.log(arr[1]); // undefined

But there is a problem here

console.log(1 in arr) // false

So if you want to assign an item in the array to undefined, you should not use the delete operator, but directly use the following assignment

arr[1] = undefined;
// 这样就可以解决上面的问题 
console.log(1 in arr) // true

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to delete attributes in object in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn