1

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 })
}

2 Answers 2

3

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

UPDATE:

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()

Sign up to request clarification or add additional context in comments.

Comments

0

Well if you're trying to test something in JSX or just to print there a fixed number of elements, this is great and worked for me. Hopefully, this will help you.

{Array.from({length:3}).map((element,index) => <p>{element} {index} </p>)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.