What is the purpose of the delete operator in Javascript?

后端 未结 6 979
一向
一向 2020-12-04 14:22

The behaviour of the delete operator seems very complicated and there are many misunderstandings about what it actually does. To me, it seems that reassigning something to <

6条回答
  •  离开以前
    2020-12-04 14:33

    The other answers are explaining the motivation behind the delete keyword. I would like to add that as of 2017, browser do deallocate memory both when deleting a property and when setting the property to undefined.

    Consider this example (source of roughSizeOfObject()):

    > var obj = {a:42,b:"b"}; roughSizeOfObject(obj)
    26
    > obj.a = undefined; roughSizeOfObject(obj)
    18
    > delete obj.a; roughSizeOfObject(obj)
    10
    > obj.b = undefined; roughSizeOfObject(obj)
    8
    > delete obj.b; roughSizeOfObject(obj)
    0
    

    The example comes from Chrome 61 (64-bit) console (note that all characters in String are internally encoded as 16-bit unsigned integer).

提交回复
热议问题