SitePoint Sponsor |
|
User Tag List
Results 1 to 5 of 5
Thread: pushing values in array ??
-
Jul 3, 2007, 04:24 #1
pushing values in array ??
Hello forums !!
I would like to push the values in array(without specifying index).
Can anybody give me the suggestion.
Note: It should be equivalent to PHP's
PHP Code:$exp_array = array();
$exp_array[] = "value1";
$exp_array[] = "value2";
...........etc
Thanks in advance to all of you.
-
Jul 3, 2007, 04:42 #2
- Join Date
- Nov 2005
- Location
- The Netherlands
- Posts
- 808
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
In Javascript you use the push method of the Array object:
Code javascript:var exp_array = new Array (); exp_array.push('value1'); exp_array.push('value2');
-
Jul 3, 2007, 04:43 #3
- Join Date
- Sep 2005
- Location
- Tanzania
- Posts
- 4,662
- Mentioned
- 2 Post(s)
- Tagged
- 0 Thread(s)
Code:var exp_array = []; exp_array.push('value1'); exp_array.push('value2');
-
Jul 3, 2007, 05:24 #4
- Join Date
- Feb 2007
- Posts
- 42
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I'm not sure why you don't want to specify indices. If you mean that you don't want to have to do:
Code:var i = 0; var a = new Array(); a[i] = 'foo'; ++i; a[i] = 'bar'; ++i
Code:var a = new Array(); a[a.length] = 'foo'; a[a.length] = 'bar';
-
Jul 3, 2007, 13:11 #5
- Join Date
- Mar 2005
- Location
- USA
- Posts
- 5,482
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
I'd use push() too. By the way, it can take multiple arguments, so you don't have to make several calls to it on the same array in a row if you don't want to.
Here's one:
Code:if(![].push){ // for old browsers that don't natively support Array.push() Array.prototype.push=function(){ for(var i=0;i<arguments.length;i++) this[this.length]=arguments[i]; return this.length; } }
We miss you, Dan Schulz.
Learn CSS. | X/HTML Validator | CSS validator
Dynamic Site Solutions
Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.
Bookmarks