The operator delete is not very commonly used in JavaScript, but its characteristics are indeed very strange.
1. Delete the object's properties, code:
The code copy is as follows:
var o = {
a: 1,
b: 2
};
delete oa;
alert(oa); //undefined
So, is deleted the attribute of the object or the attribute value of the object? I began to think that the delete should be the value, because the result is undefined and there is no error. But in fact, my opinion is wrong, give an example:
The code copy is as follows:
var o = {};
var a = {
pro: "zhenn"
};
oc = a;
delete oc; //Delete the property a of object o
console.log(oc); // undefined
console.log(a.pro); // zhenn
Through the above code, it is not difficult to see that after delete oc, the value pointed to by oc is not deleted, that is, object a still exists, otherwise a.pro should not be able to pass the compilation level. Speaking of this, it can be understood that delete deletes the attributes of an object in this way, which is actually equivalent to deleting a reference to the attribute value in the object, but this value is still in the object stack!
2. For the operation of the array, look at the code first:
The code copy is as follows:
var arr = [1,2,3];
delete arr[2];
console.log(arr.length); // 3
console.log(arr); // [1,2,undefined]
It has been proved again that delete does not really delete the element, it just deletes the key value corresponding to the element. In order to further understand the essence of delete, compare it with the pop method in Array. as follows:
The code copy is as follows:
var arr = [1,2,3];
arr.pop();
console.log(arr); // [1,2]
console.log(arr.length) // 2
The truth should be revealed now.
3. The above operations on objects and arrays are easy to understand, but the operations on variables are inevitably difficult to understand. The code is as follows:
The code copy is as follows:
var a = 1;
delete a;
alert(a); // 1
function fn(){ return 42; }
delete fn;
alert(fn()); // 42
b = 2;
delete b;
alert(b); // b is not defined;
It is difficult to explain. It is also a global variable, but the variable b declared with var cannot be deleted. It is impossible to say that delete is very strange. In the explanation given by ECMA, it only means that variables declared through var and functions declared through function have the DontDelete feature and cannot be deleted.