Nitin Labhishetty
Nitin Labhishetty

Reputation: 1348

selective filling of arrays in javascript

If a create a new array in javascript such as:

var arr=[];

Is there a method to add elements to this array at selected locations eg. I want to add elements at index 3,5,6,10 in the above created array. Rest of the locations are empty/ undefined.

If yes, are there any that problems could arise by using such an array?

Upvotes: 1

Views: 66

Answers (1)

thefourtheye
thefourtheye

Reputation: 239573

You should be using an object in this case.

var arrayLikeObject = {};

arrayLikeObject[3] = "a";
arrayLikeObject[5] = "b";
...

You can use an array object as well, like this

var array = [];

but the problem is, you ll have the rest of the array elements as missing.

var array = [];
array[3] = "a";
array[5] = "b";
console.log(array);
# [ , , , 'a', , 'b' ]

You ll be able to iterate them with a regular for loop like this

for(var i = 0; i < array.length; i += 1) {
   console.log(array[i]);
}
# undefined
# undefined
# undefined
# a
# undefined
# b

but, Array.prototype.forEach, Array.prototype.map etc will ignore the missing elements.

array.forEach(function(currentItem) {
    console.log(currentItem);
});
# a
# b

Upvotes: 3

Related Questions