views:

309

answers:

7

In PHP, I'd do something like:

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

How would I do the same thing in jQuery?

+6  A: 

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

var arr = new Array();
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
which is exactly how the "jQuery" object returned by `$()` works
Russ Cam
Well, I'm sure there's a plugin which allows you to do that with jQuery :P
Ben Shelock
How about `[]` instead of `new Array()` and `{}` instead of `new Object()`...
J-P
@J-P: sure, why not. I'm just trying to be as clear as possible in the example.
David
Yeah Russ, that's true. Reading the jQuery source is actually quite pleasant I think.
darkporter
@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
@Justin: Actually, it's slightly faster: http://mir.aculo.us/2009/12/24/extreme-javascript-performance-video (slide 21 onwards)
Will Vousden
@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
+2  A: 

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

e.g.

var primates = new Array();
primates.push('monkey');
primates.push('chimp');
mopoke
+3  A: 

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
+1 for `[]` instead of `new Array()`.
BalusC
Why thank you sir. Edited to indicate that I know *why* :)
Mike
A: 
array = ["value1", "value2", "value3"]

it's not so much jquery as javascript

Antony Hatchkins
that's not *adding* any values to an array, that's creating an array with some values already in it.
nickf
I wouldn't downvote for that, but thanks for at least explaining your opinion
Antony Hatchkins
A: 

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");
roosteronacid
I'd call it a "framework"... and it's not a subset either.
Mark
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
@Ionut G. Stan: I am initializing the array by doing `var array = [];`
roosteronacid
@Mark: I'd call jQuery a library. It is advertised as such and not as a framework.
Tim Down
@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
+1  A: 

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] = "valueI";

or by using splice

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

Choose one you need.

nemisj
+2  A: 

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