113

I know how to initliaize one but how do add I items to an Array? I heard it was push() maybe? I can't find it...

5
  • What do you want to add to what array?
    – gen_Eric
    May 2, 2011 at 19:59
  • 4
    Are you asking how to add elements to an Array, or how to add elements to a jQuery object?
    – Phrogz
    May 2, 2011 at 20:01
  • @Jahkr: Then what does jQuery have to do with it? May 2, 2011 at 20:08
  • I'm doing the arrays in jQuery...
    – test
    May 2, 2011 at 20:09
  • 3
    @Jahkr: You're also probably sitting on a chair whilst doing it, but that doesn't mean that the question is relevant to Ikea. Don't be misled thinking that jQuery is a separate language; it is not. You're still writing Javascript. You just happen to be using things from the jQuery library (in other parts of your code). May 2, 2011 at 20:10

5 Answers 5

320

For JavaScript arrays, you use push().

var a = [];
a.push(12);
a.push(32);

For jQuery objects, there's add().

$('div.test').add('p.blue');

Note that while push() modifies the original array in-place, add() returns a new jQuery object, it does not modify the original one.

1
  • 18
    +1 for explaining both JavaScript and jQuery's method and their fundamental difference. I came here for $.add() and got just a little bit more.
    – Sam
    Feb 1, 2014 at 0:21
30

push is a native javascript method. You could use it like this:

var array = [1, 2, 3];
array.push(4); // array now is [1, 2, 3, 4]
array.push(5, 6, 7); // array now is [1, 2, 3, 4, 5, 6, 7]
14

You are right. This has nothing to do with jQuery though.

var myArray = [];
myArray.push("foo");
// myArray now contains "foo" at index 0.
3
  • nice, but how do I add foo at index 'customString' ? Oct 21, 2012 at 15:58
  • ha! I found it myArray.push( {'index':'value'} ); Oct 21, 2012 at 16:01
  • But that is no longer array then, myArray turns into object?
    – SubjectX
    Nov 12, 2015 at 12:24
4

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.
2

just it jquery

var linkModel = {
            Link: "",
            Url: "",
            Summary: "",
        };

var model = [];
for (let i = 1; i < 2; i++) {
    linkModel.Link = "Test.com" + i;
    linkModel.Url= "www.Test.com" + i;
    linkModel.Summary= "Test is add" + i;
    model.Links.push(linkModel);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.