Home>

delete is a unary operatorIt is used to delete object attributes or array elements.Just like the assignment, increment, and decrement operators,delete also has side effects,It is used for delete operations,Not for returning a value,E.g:

var o={x:1, y:2};//define an object
delete o.x;//delete an attribute
"x" in o //=>false:this attribute no longer exists in the object
var a=[1,2,3];//define an array
delete a [2];//delete the last array element
2 in a;//=>false:element 2 no longer exists in the array
a.length //=>3:Note that the array length has not changed,Although the previous line of code is removed

have to be aware of is,Deleting attributes or deleting array elements is more than just setting an undefined value. When deleting an attribute,This attribute will no longer exist.Reading a non-existent property returns undefined, but you can use the in operator (see Section 4.9.3) to detect whether the property exists in the object.

delete wants his operand to be an lvalue,If it is not lvalue,Then delete will do nothing and return true. Otherwise, delete will attempt to delete the specified lvalue. If the deletion is successful,delete will return true. However, not all attributes can be deleted. Some built-in core and client attributes cannot be deleted.Variables declared by the user through the var statement cannot be deleted.Similarly, functions and function parameters defined by function statements cannot be deleted.

In ecmascript 5 strict mode,If the delete operand is illegal,Such as variables, functions, or function parameters,The delete operation will throw a syntaxerror exception, which will only work if the operand is an attribute access expression (see Section 4.4).In strict mode,delete deletes a non-configurable attribute (see Section 6.7) and throws a type error exception.In non-strict mode,These delete operations will not report an error,It simply returns false to indicate that the operand cannot perform a delete operation.

Here are some examples of the delete operator:

var o={x:1, y:2};//define a variable,Initialized as an object
delete o.x;//Delete an object attribute,Returns true
typeof o.x;//Attribute does not exist,Returns "undefined"
delete o.x;//Delete non-existing attributes,Returns true
delete o;//Cannot delete variables declared through var,Returns false
//In strict mode,Will throw an exception delete 1;//parameter is not an lvalue,Returns true
this.x=1;//Define a property for the global object,Not used here
var delete x;//try to delete it,Return true in non-strict mode
//Exception will be thrown in strict mode,Use "delete this.x" instead
x;//runtime error,X is not defined
  • Previous Conceptual knowledge of Python tuples
  • Next wxPython implement drawing board