270

In PHP, I'd do something like:

$array = array();
$array[] = "value1";
$array[] = "value2";
$array[] = "value3";

How would I do the same thing in JavaScript?

Luke
  • 22,826
  • 31
  • 110
  • 193
Andrew
  • 12,172
  • 16
  • 46
  • 61

8 Answers8

406

You don't need jQuery for that. Use regular javascript

var arr = new Array();
// or var arr = [];
arr.push('value1');
arr.push('value2');

Note: In javascript, you can also use Objects as Arrays, but still have access to the Array prototypes. This makes the object behave like an array:

var obj = new Object();
Array.prototype.push.call(obj, 'value');

will create an object that looks like:

{
    0: 'value',
    length: 1
}

You can access the vaules just like a normal array f.ex obj[0].

David Hellsing
  • 106,495
  • 44
  • 176
  • 212
  • 5
    which is exactly how the "jQuery" object returned by `$()` works – Russ Cam Jan 03 '10 at 23:34
  • 1
    Well, I'm sure there's a plugin which allows you to do that with jQuery :P – Ben Shelock Jan 03 '10 at 23:37
  • 81
    How about `[]` instead of `new Array()` and `{}` instead of `new Object()`... – James Jan 03 '10 at 23:58
  • 7
    @J-P: sure, why not. I'm just trying to be as clear as possible in the example. – David Hellsing Jan 04 '10 at 00:03
  • Yeah Russ, that's true. Reading the jQuery source is actually quite pleasant I think. – jpsimons Jan 04 '10 at 00:23
  • @J-P: While most find it preferable to read and write, there is no real benefit to using the literal notation when creating empty containers. – Justin Johnson Jan 04 '10 at 01:26
  • 3
    @Justin: Actually, it's slightly faster: http://mir.aculo.us/2009/12/24/extreme-javascript-performance-video (slide 21 onwards) – Will Vousden Jan 04 '10 at 01:30
  • @Inquisitor: Interesting. In my tests, the difference was smaller on average coming in at only 0.001. I did some tests to measure the difference in time to populate an empty array (`a1 = []`) and a pre-sized array (`a2 = new Array(1024)`), but the literal notation was still faster, which is curious to me. – Justin Johnson Jan 04 '10 at 01:57
109

This has nothing to do with jQuery, just JavaScript in general.

To create an array in JavaScript:

var a = [];

Or:

var a = ['value1', 'value2', 'value3'];

To append values on the end of existing array:

a.push('value4');

To create a new array, you should really use [] instead of new Array() for the following reasons:

  • new Array(1, 2) is equivalent to [1, 2], but new Array(1) is not equivalent to [1]. Rather the latter is closer to [undefined], since a single integer argument to the Array constructor indicates the desired array length.
  • Array, just like any other built-in JavaScript class, is not a keyword. Therefore, someone could easily define Array in your code to do something other than construct an array.
Mike
  • 4,976
  • 2
  • 18
  • 11
36

Array is a JavaScript native object, why don't you just try to use the API of it? Knowing API on its own will save you time when you will switch to pure JavaScript or another framework.

There are number of different possibilities, so, use the one which mostly targets your needs.

Creating array with values:

var array = ["value1", "value2", "value3"];

Adding values to the end

var array = [];
array.push("value1");
array.push("value2");
array.push("value3");

Adding values to the begin:

var array = [];
array.unshift("value1");
array.unshift("value2");
array.unshift("value3");

Adding values at some index:

var array = [];
array[index] = "value1";

or by using splice

array.splice(index, 0, "value1", "value2", "value3");

Choose one you need.

VisioN
  • 143,310
  • 32
  • 282
  • 281
nemisj
  • 11,562
  • 2
  • 25
  • 23
  • The one with indexes is not working for me. I am using it inside a map function $('select[id^="filter_"]').map(function () { var name = $(this).prop('name'); filters[name] = $(this).val(); – Happy Coder Dec 05 '13 at 11:12
14

There are several ways:

Instantiating the array:

var arr;

arr = new Array(); // empty array

// ---

arr = [];          // empty array

// ---

arr = new Array(3);
alert(arr.length);  // 3
alert(arr[0]); // undefined

// ---

arr = [3];
alert(arr.length);  // 1
alert(arr[0]); // 3

Pushing to the array:

arr = [3];     // arr == [3]
arr[1] = 4;    // arr == [3, 4]
arr[2] = 5;    // arr == [3, 4, 5]
arr[4] = 7;    // arr == [3, 4, 5, undefined, 7]

// ---

arr = [3];
arr.push(4);        // arr == [3, 4]
arr.push(5);        // arr == [3, 4, 5]
arr.push(6, 7, 8);  // arr == [3, 4, 5, 6, 7, 8]

Using .push() is the better way to add to an array, since you don't need to know how many items are already there, and you can add many items in one function call.

nickf
  • 537,072
  • 198
  • 649
  • 721
12

You can use the .push() method (which is standard JavaScript)

e.g.

var primates = new Array();
primates.push('monkey');
primates.push('chimp');
mopoke
  • 10,555
  • 1
  • 31
  • 31
3

Indeed, you must initialize your array then right after that use array.push() command line.

var array = new Array();
array.push("first value");
array.push("second value");
Sitepor500.com.br
  • 388
  • 1
  • 5
  • 11
2
array = ["value1", "value2", "value3"]

it's not so much jquery as javascript

Antony Hatchkins
  • 31,947
  • 10
  • 111
  • 111
1

jQuery is an abstraction of JavaScript. Think of jQuery as a sub-set of JavaScript, aimed at working with the DOM. That being said; there are functions for adding item(s) to a collection. I would use basic JavaScript in your case though:

var array;

array[0] = "value1";
array[1] = "value2";
array[2] = "value3";

... Or:

var array = ["value1", "value2", "value3"];

... Or:

var array = [];

array.push("value1");
array.push("value2");
array.push("value3");
cllpse
  • 21,396
  • 37
  • 131
  • 170
  • 6
    I'd call it a "framework"... and it's not a subset either. – mpen Jan 03 '10 at 23:28
  • You should initialize the `array` variable to an `Array` object in your first example, otherwise it will be `undefined` and you can't call `push` on it. – Ionuț G. Stan Jan 03 '10 at 23:32
  • @Ionut G. Stan: I am initializing the array by doing `var array = [];` – cllpse Jan 04 '10 at 00:10
  • 2
    @Mark: I'd call jQuery a library. It is advertised as such and not as a framework. – Tim Down Jan 04 '10 at 01:06
  • @roosteronacid, I meant the first example. I don't know how that `push` observation slipped in my previous comment. I somehow mixed the first and the third examples. – Ionuț G. Stan Jan 04 '10 at 05:15