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

2
  • @AndreasKöberle - Please note that in my question the array size is unknown Commented Jan 18, 2013 at 7: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. Commented Sep 4, 2019 at 1:03

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

But this does not create an array of unknown size...
@Belgi updated the code. please check now
Thanks, but "numberofIndexes" is not known
@belgi You just need to give an initial value, you can always expand the array later.
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

5 Comments

Yes, this should be 0. Can I make it print 0 ? thanks for the help!
@Belgi I edited answer... not so good approach, but maybe you can use it.
Thanks! by the way: I can just use "Array.prototype..." just like this or do I need to include something (like in C/C++) ?
@Belgi You don't need to include anything. Array is built-in class.
Messing with the prototypes of Array, Date, etc. is not a good practice. Even for a short piece of code... if it's short, a separated function to this wouldn't hurt.
-1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.