'Freezing' Arrays in Javascript?

前端 未结 3 931
轻奢々
轻奢々 2021-01-01 08:24

Since the ECMA-262 specifications Javascript has gained the Object.freeze() method, which allows for objects, whose properties can not be changed, added or removed.

相关标签:
3条回答
  • 2021-01-01 09:20

    Yes, it is applicable to arrays too.

    const arr = [1,2,3,4];
    Object.freeze(arr);
    Object.isFrozen(arr)// true
    arr.push(5) // you will get a type error
    arr.pop() // you will get a type error
    
    0 讨论(0)
  • 2021-01-01 09:21

    Instead of freeze, use spread operator to copy things without modifying them (if you are using a transpiler, of course):

    const second = {
      ...first,
      test: 20
    }
    
    0 讨论(0)
  • 2021-01-01 09:23

    Yes, freeze should work for Arrays, the behavior you are experiencing is clearly an implementation bug.

    This bug might be related to the fact that array objects implement a custom [[DefineOwnProperty]] internal method (the magic that makes the length property work).

    I just tested it on two implementations and it works properly (Chrome 16.0.888, and Firefox Aurora 8.02a).

    About your second question, well, array objects inherit from Array.prototype which inherits from Object.prototype, for example, you can access non shadowed methods from Object.prototype directly on array objects:

    ['a'].hasOwnProperty('0'); // true
    

    But this isn't related about how the typeof works, this operator will return 'object' for any object intance, regardless its kind, and for the null value, which people has always complained about.

    The rest of possible return values of the typeof operator, correspond to the primitive types of the language, Number, String, Boolean, Symbol and Undefined.

    0 讨论(0)
提交回复
热议问题