First, the grammar
The expression following the delete must give a reference to a property, such as
var o = {a:1};
Delete o.a; Here o.a is a reference to the property A of object o
You can use a separate property name only in the WITH statement
Copy Code code as follows:
second, the return value of the delete
Delete is a normal operator and returns TRUE or false. Rule is: Returns False when the property of the object being deleted is present and cannot be removed, otherwise returns true. One feature here is that when an object property does not exist, it returns true, so the return value is not exactly the same as whether the deletion was successful or not.
Copy Code code as follows:
var o = {a:1};
Delete o.a; Returns True
var B = 2;
Delete b;//returns the FALSE,ECMA rule convention: Variables declared with VAR and function cannot be delete
Iii. What are the circumstances in which delete is not allowed
The variables mentioned in the previous example for Var and function declarations cannot be deleted, but implicit declarations can be removed
Copy Code code as follows:
Function C () {return 12;}
Delete c;//returns false
D = function () {return 12;}
Delete d;//returns True
You cannot delete a property inherited from a prototype chain, but you can delete a property on the prototype chain
Copy Code code as follows:
function Foo () {}
Foo.prototype.bar = 42;
var foo = new Foo ();
Delete Foo.bar; Returns true, but does not work
alert (foo.bar); Alerts 42, Attributes are inherited
Delete Foo.prototype.bar; Delete Attribute bar on prototype
alert (foo.bar); Alerts "Undefined", property no longer exists, cannot be inherited
Iv. Special Cases
Copy Code code as follows:
In the code that eval executes, there are variables declared through Var and function, which can be delete
Eval ("var a=1");
Delete A;
alert (a); The report does not define an error
If the declaration is made within a closure in the eval execution code, the variable cannot be delete
Eval ("(function () {var a=1;delete A; return A;}) () ");//1
Five, delete array elements
Delete its elements from an array without affecting the length of the array
Copy Code code as follows:
var arr = [' Yuyin ', ' Suhuan ', ' baby '];
Delete Arr[0];
alert (arr.length);//alert 3
The key value of the delete is already not part of the array, but it can still be accessed, and its value is undefined.
Copy Code code as follows:
var arr = [' Yuyin ', ' Suhuan ', ' baby '];
Delete Arr[0];
0 in Arr; False
Alert (arr[0]);//undefined
Arr[0] = = = Undefined;//true
Compare directly to assigning key values undefined
Copy Code code as follows:
var arr = [' Yuyin ', ' Suhuan ', ' baby '];
Arr[0] = undefined;
0 in Arr; True
Alert (arr[0]);//undefined
Arr[0] = = = Undefined;//true
You can see that the delete operation simply deletes the key value attribute from the array and the array itself is an object, and this is a good idea. If you need to preserve key values, you can assign values using undefined.