开发者

javascript property deletion

开发者 https://www.devze.com 2023-03-07 02:16 出处:网络
Just wondering about this one : What开发者_Python百科s the difference, or is there a difference at all, between :

Just wondering about this one :

What开发者_Python百科s the difference, or is there a difference at all, between :

delete obj.someProperty

and

obj.someProperty=undefined


The second version sets the property to the existing value undefined while the first removes the key from the object. The difference can be seen when iterating over the object or using the in keyword.

var obj = {prop: 1};
'prop' in obj; // true
obj.prop = undefined;
'prop' in obj; // true, it's there with the value of undefined
delete obj.prop;
'prop' in obj; // false


The difference will be realized when iterating over the object. When deleting the property, it will not be included in the loop, whereas just changing the value to undefined will include it. The length of the object or number of iterations will be different.

Here is some great (albeit advanced) information on deleting in JavaScript:

http://perfectionkills.com/understanding-delete/


Using delete will actually remove the key itself from the object. If you set the value to undefined, they key still exists, but the value is the only thing that has changed.


The former will actually delete the property, the latter will leave it but set it to undefined.

This becomes significant if you loop over all the properties (for (props in obj) { }) or test for the existence of one (if ('someProperty' in obj) {})

0

精彩评论

暂无评论...
验证码 换一张
取 消