Home > Web Front-end > JS Tutorial > Introduction to the deletion method of object property in JavaScript_javascript skills

Introduction to the deletion method of object property in JavaScript_javascript skills

WBOY
Release: 2016-05-16 16:23:12
Original
1275 people have browsed it

In JavaScript, you can use the delete operator to delete a property in an object:


Copy code The code is as follows:

var t = {a:42, b:26};
console.log(t);//Object {a=42, b=26}
delete t.a;
console.log(t);//Object {b=26}


The limitation of this property deletion operation is that the delete operator can only delete all the properties of the object itself, and cannot delete the properties inherited from the prototype object. If you want to delete the property in the prototype object, you must explicitly obtain the prototype object and then perform the operation in the prototype object:


Copy code The code is as follows:

var o = {x:1, y:2};
var a = Object.create(o);
a.z = 3;
console.log(a);//Object {z=3, x=1, y=2}
delete a.x;//Can NOT delete inherited property
console.log(a);//Object {z=3, x=1, y=2}
delete a.z;//Can delete own property
console.log(a);//Object {x=1, y=2}
delete a.__proto__.x;
console.log(a);//Object {y=2}


If a property in a prototype object is deleted, all objects that inherit from the prototype object will be affected.

For the return value of delete operation, JavaScript follows the following rules:

1. If the delete operation is successful, return true.
2. If the delete operation has no effect (for example, the property to be deleted does not exist), it will also return true.
3. If you want to delete a property whose configurable attribute is false, a TypeError error will be reported in strict mode, and false will be returned in non-strict mode.
If the delete operator acts on the property of the global object, then in non-strict mode, the global object in the code can be omitted:

Copy code The code is as follows:

this.c = 42;
delete c;//equal to delete this.c;

It should be noted that in strict mode, the above writing method will throw a SyntaxError.

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template