1

Is there an equivalent method in Javascript arrays or ArrayList to Java's ensureCapacity? I am translating a certain Java code containing this method to Javascript, and couldn't find any equivalent to it. Thanks in advance

elbereth
  • 37
  • 1
  • 4
  • 10
  • No, there is no official one, but engines are pretty smart anyway. Some of them have an optimisation to pre-allocate memory when you assign a `.length`, but it doesn't make much difference. – Bergi Sep 24 '14 at 13:59

2 Answers2

1

It is possible to initialize an array with a specific size:

var array = new Array(n);

If your array has already been initialized you can, as mentioned in comments, set the length of the array using the length property:

array.length = n;

However, the performance gains, if any, seems negligble. Here is a thread discussing this.

Community
  • 1
  • 1
Frederik Wordenskjold
  • 10,031
  • 6
  • 38
  • 57
0

var fruits = ['apple', 'pineapple'];
console.log(fruits.length, fruits);//2 ["apple", "pineapple"] 
fruits.length = fruits.length + 4; //increase by 4
console.log(fruits.length, fruits);//6 ["apple", "pineapple"]
Open console for more ...