View Full Version : How to use array.push with a custom index?

09-25-2011, 04:24 PM
How do I use array.push to add an object with a custom index in an array?

I have this script but it doesnt work. Chrome's Javascript console is not outputting errors

var tempList = new Array();

var split = $('#itemid').val().split('_');
var itemid = split['0'];
var lbs = $('#lbs').val();
tempList.push(tempList['itemid'] = lbs);
for (var i=0; i<=(tempList.length - 1); i++){
if (i==0){
var list = tempList[i]+ '<br />';
var list = list + tempList[i]+ '<br />';

09-25-2011, 05:32 PM
You don't.

Push just adds a new element at the end of the array

// myArray[0] --> 'hi', myArray[1] --> 'bye'
var myArray = [];

If you want to add an element at a specific index, be specific about it

// myArray[0] --> 'hi', myArray[1] --> undefined, myArray[2] --> 'bye'
var myArray = [];
myArray[2] = 'bye';

Furthermore: Whenever you find the need to make sparse arrays in Javascript, ask yourself: Am I really trying to create an hash? If so you should use an object instead (not an array as you would in php).

var myHash = {};
myHash['rabbit'] = 'carrots';
myHash['dog'] = 'bone';
document.write('My rabbit eats ' + myHash['rabbit']);

which can also be written like this (if your hash keys aren't variables):

var myHash = {};
myHash.rabbit = 'carrots';
myHash.dog = 'bone';
document.write('My rabbit eats ' + myHash.rabbit);

09-27-2011, 04:13 PM

The solution I was looking for was the hash.