Home  >  Article  >  Web Front-end  >  The weird delete operator in JavaScript_javascript tips

The weird delete operator in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:09:561082browse

The delete operator is not very commonly used in JavaScript, but its characteristics are indeed very strange.

1, delete the attributes of the object, code:

Copy code The code is as follows:

var o = {
a: 1,
b: 2
};
delete o.a;
alert(o.a); //undefined

So, does delete delete the object's attributes or the object's attribute values? I began to think that what was deleted should be the value, because the result was undefined and no error was reported. But in fact, my view is wrong, for example:

Copy code The code is as follows:

var o = {};
var a = {
pro: "zhenn"
};
o.c = a;
delete o.c; //Delete the 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 that after deleting o.c, the value pointed to by o.c is not deleted, that is, object a still exists, otherwise a.pro should not pass the compilation level. Speaking of which, you can understand that delete deletes the attributes of the object. 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 operations on arrays, look at the code first:

Copy code The code is as follows:

var arr = [1,2,3];
delete arr[2];
console.log(arr.length); // 3
console.log(arr); // [1,2,undefined]

Once again, it is proved that delete does not actually delete the element, but only deletes the key value corresponding to the element. In order to further understand the nature of delete, compare it with the pop method in Array. As follows:

Copy code The code is as follows:

var arr = [1,2,3];
arr.pop();
console.log(arr); // [1,2]
console.log(arr.length) // 2

Now the truth should be revealed.

3. The above operations on objects and arrays are easy to understand, but the operation of variables is inevitably confusing. The code is as follows:

Copy code The code 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’s hard to explain. It’s also a global variable. The one declared with var cannot be deleted, but the directly declared variable b can be deleted. I have to say that delete is very strange. In the explanation given by ECMA, it is only It means that variables declared through var and functions declared through function have the DontDelete attribute and cannot be deleted.

Statement:
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