Is it possible to create a fixed length array in javascript?

后端 未结 9 1122
春和景丽
春和景丽 2020-12-03 00:59

Is it possible, in Javascript, to create an array whose length is guaranteed to remain the same?

For example, the array A is created with length 2. Subs

9条回答
  •  星月不相逢
    2020-12-03 01:41

    The current answer is YES, you can. There are severals ways to do that, but some web browsers has it's own "interpretation".

    1. Solution tested with FireFox Mozzila Console:

    var x = new Array(10).fill(0);
    // Output: undefined
    Object.freeze(x);
    // Output: Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
    x.push(11)
    // Output: TypeError: can't define array index property past the end of an array with non-writable length
    x.pop()
    // Output: TypeError: property 9 is non-configurable and can't be deleted [Learn More]
    x[0]=10
    // Output: 10 // You don't throw an error but you don't modify the array
    x
    // Output: Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]   

    Is important to notice that if the array are object, you need to do, deep freeze instead. The code of deepfreeze is here.

    1. A Class that wraps an Array (it's better if you don't want to throw an exception)

    2. With ES2015 code should work the follow solution but it doesn't:

    var x = new Array(10).fill(0);
    Object.freeze( x.length );
    x.push(3);
    console.log(x);
    Check this page in the section Note

提交回复
热议问题