I create arrays using this method. I want to create fixed-length array that contains only 20 elements.
this.state{
array:[]
}
onInputChange(e){
const name=e.target.value;
this.setState({ array:name })
}
You can use Array#fill
const arr = Array(20).fill(1)
console.log(arr)
This will not be fixed as you can't fix an array's length, but you can do according checks in order not to push anything to this array once created. You can create a fixed Object however, using Object.seal
Apparently, you can use Object.seal() on arrays too:
const object1 = Array(10).fill(0)
Object.seal(object1);
object1[2] = 24;
console.log(object1)
object1.push(8)
console.log(object1)
object1.pop()
console.log(object1)
And if you use Object.freeze() it also doesn't allow any changes in the array. You can still change the values of indices using seal()