Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts

    How to use array.push with a custom index?

    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

    Code:
    var tempList = new Array();
    $('#add').click(function(){
    
        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 />';
            } 
            else{
                var list =  list + tempList[i]+ '<br />';
            }
        }
        alert(list);
    });

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Location
    Sweden
    Posts
    154
    Thanks
    1
    Thanked 22 Times in 22 Posts
    You don't.

    Push just adds a new element at the end of the array
    Code:
    // myArray[0] --> 'hi', myArray[1] --> 'bye'
    var myArray = [];
    myArray.push('hi');
    myArray.push('bye');
    If you want to add an element at a specific index, be specific about it
    Code:
    // myArray[0] --> 'hi', myArray[1] --> undefined, myArray[2] --> 'bye'
    var myArray = [];
    myArray.push('hi');
    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).
    Code:
    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):
    Code:
    var myHash = {};
    myHash.rabbit = 'carrots';
    myHash.dog = 'bone';
    document.write('My rabbit eats ' + myHash.rabbit);

  • Users who have thanked ironboy for this post:

    JustBob (09-27-2011)

  • #3
    New Coder
    Join Date
    Sep 2011
    Posts
    16
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Thanks...

    The solution I was looking for was the hash.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •