search
HomeWeb Front-endJS TutorialHow to delete attributes in object in 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'
}

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor