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 Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft