SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    10
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    array push element

    hi,
    i need to add 'GGG' to an existing array, but at a certain position without overwriting other elements. is there a way to do this without looping over the array and reinsert the elements?

    thanks

    pete

    existing array: 'XXX','YYY','TTT');
    final array should be: 'XXX','GGG','YYY','TTT');


    Code:
    var myArray = new Array('XXX','YYY','TTT');
    
    //get position of YYY
    var pos = myArray.indexOf('YYY');
    
    //add GGG at the postion of YYY
    myArray[pos] = 'GGG';
    
    // how can i readd YYY,TTT

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Use splice.

    Code:
    var myArray = ['XXX','YYY','TTT'];
    var pos = myArray.indexOf('YYY');
    
    myArray.splice(pos,0, 'GGG');
    // the second argument is the number of items to remove- 0 in this case

    alert(myArray)

    /* returned value: (Array)
    XXX,GGG,YYY,TTT
    */


Bookmarks

Posting Permissions

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