Strange delete operators and JavaScript operators in javascript
The delete operator is not very common in javascript, but its features are indeed very strange.
1. Delete the attributes of an object. Code:
Copy codeThe Code is as follows:
Var o = {
A: 1,
B: 2
};
Delete o.;
Alert (o. a); // undefined
In the end, whether the delete operation deletes the object attribute or the object attribute value, I began to think that the deletion should be a value because the result is undefined and no error is reported. But in fact, my opinion is wrong. For example:
Copy codeThe Code is as follows:
Var o = {};
Var a = {
Pro: "zhenn"
};
O. c =;
Delete o. c; // delete attribute a of object o
Console. log (o. c); // undefined
Console. log (a. pro); // zhenn
Through the above Code, it is not difficult to see in the delete o. c. the value pointed to by c, that is, object a still exists; otherwise,. pro should not be able to compile this function. Speaking of this, we can understand the delete object attribute in this way. In fact, it is equivalent to deleting the reference to the attribute value in the object, but this value is still in the object stack!
2. For Array Operations, first look at the Code:
Copy codeThe Code is as follows:
Var arr = [1, 2, 3];
Delete arr [2];
Console. log (arr. length); // 3
Console. log (arr); // [1, 2, undefined]
It is proved again that delete does not actually delete the element, but only deletes the key value corresponding to the element. To further identify the nature of delete, we can compare it with the pop method in Array. As follows:
Copy codeThe Code is as follows:
Var arr = [1, 2, 3];
Arr. pop ();
Console. log (arr); // [1, 2]
Console. log (arr. length) // 2
This should be clear.
3. the above operations on objects and ArraysBut the variable operations are hard to understand. The Code is as follows:
Copy codeThe Code is as follows:
Var a = 1;
Delete;
Alert (a); // 1
Function fn () {return 42 ;}
Delete fn;
Alert (fn (); // 42
B = 2;
Delete B;
Alert (B); // B is not defined;
It's hard to explain. It's also a global variable. The variable declared with var cannot be deleted, but the directly declared variable B can be deleted. It cannot be said that delete is a strange thing, in the explanation given by ECMA, only variables declared through var and functions declared through function have the DontDelete feature and cannot be deleted.