1

Possible Duplicate:
Most efficient way to create a zero filled JavaScript array?

I wish to create an array in JS, the array will store integer value.

I would like to increment some of the values by 1, o at first I would like that each cell in the array would contain 0

Is it possible to do it in JS ?

Note: The array is of unknown size upon creation

Community
  • 1
  • 1
Belgi
  • 14,542
  • 22
  • 58
  • 68
  • @AndreasKöberle - Please note that in my question the array size is unknown – Belgi Jan 18 '13 at 07:36
  • Did you mean to say that this multidimensional array, and you want to initialize each element inside to 0 so that you can increment each item without getting the undefined problem? If so, then you'll want to edit this question to explain that better, as well as the title, and then flag a moderator to request reopening this question as a separate question than the one they think is a duplicate. – Volomike Sep 04 '19 at 01:03

3 Answers3

2
var arr = [0,0,0,0];

incrementIndex(1,0);
incrementIndex(2,1);

function incrementIndex(index, value)
{
  arr[ index ] = arr[ index ] + value;


}

Edit:

var arr = returnArray(10);

function returnArray(numberofIndexes)
{
  var arr = new Array();
  for ( var counter = 0; counter < numberOfIndexes; counter++)
  {
     arr.push(0);
  }
  return arr;
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1
Array.prototype.increaseAt = function(index){
    this[index] = this[index]+1 || 1
};
Array.prototype.getValueAt = function(index){
    return this[index] || 0;
};

Use it like:

var testArray = [];
testArray.increaseAt(3);
console.log(testArray.getValueAt(3)); // 1
console.log(testArray.getValueAt(1)); // 0
SangYeob Bono Yu
  • 821
  • 4
  • 16
-1

You can access item of array by index of this item, like this item[index] += 1

Stiger
  • 1,189
  • 2
  • 14
  • 29