Home Web Front-end JS Tutorial How to delete attributes in object in javascript

How to delete attributes in object in javascript

Jun 09, 2021 pm 03:24 PM
delete javascript

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'
}
Copy after login

You can remove properties from this object using the following command

delete car.brand
Copy after login

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']
Copy after login

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']
Copy after login

For example:

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

delete person.name

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

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
Copy after login

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属性成功删除
Copy after login
接下来看: 
console.log(p.name) => // '李四' 依然可以访问到
Copy after login

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
Copy after login
// 声明函数
var fn = function () {
    console.log(1);
}
delete fn // 严格模式下抛出语法异常  SyntaxError
fn() // 1 非严格模式下delete失效, 函数依然存在

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

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();
Copy after login
// 局部作用域声明函数
var fn = function() {
    var fn2 = function() {
        console.log(1);
    };
    delete fn2 // 严格模式下抛出语法异常 SyntaxError 
    console.log(delete fn2); // false 非严格模式下
    fn2(); // 1
}
fn();
Copy after login

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
Copy after login

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
Copy after login
delete Array.prototype //严格模式下抛出异常
console.log(Array.prototype) // 非严格模式下,prototype依然存在, 可以自己试试了,自己动手,丰衣足食
console.log(Array.prototype.join); // 非严格模式下,join方法依然存在
Copy after login

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
Copy after login

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
Copy after login

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
//     }
Copy after login
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
//     }
Copy after login

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
Copy after login

But there is a problem here

console.log(1 in arr) // false
Copy after login

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
Copy after login

[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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles