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

后端 未结 9 1112
春和景丽
春和景丽 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:44

    We can use closure for this type of problem. We are just fixed the array size and return a function from a function.

        function setArraySize(size){
       return function(arr, val) {
          if(arr.length == size) {
              return arr;    
           } 
       arr.push(val);
       return arr;
       }
    }
    let arr = [];
    let sizeArr = setArraySize(5); // fixed value for fixed array size.
    sizeArr(arr, 1);
    sizeArr(arr, 2);
    sizeArr(arr, 3);
    sizeArr(arr, 4);
    sizeArr(arr, 5);
    sizeArr(arr, 6);
    console.log('arr value', arr);

提交回复
热议问题