Difference between revisions of "Arrays (javascript)"

From HalfgeekKB
Jump to navigation Jump to search
 
Line 26: Line 26:
 
  a = new Array('B','C','D');
 
  a = new Array('B','C','D');
 
  b = new Array('G','H','I');
 
  b = new Array('G','H','I');
 
+
 
  c = new Array('A').concat(a,'E','F',b,'J','K');
 
  c = new Array('A').concat(a,'E','F',b,'J','K');
 
  // c contains 'A','B','C','D','E','F','G','H','I','J','K'
 
  // c contains 'A','B','C','D','E','F','G','H','I','J','K'

Revision as of 16:32, 14 April 2005

Some Perl analogues

Perl                       JS
@a = (1,2,3);              a = new Array(1,2,3);
@a = (@b,@c,'d');          a = b.concat(c,'d');
@a = ('x',@b,'y',@c);      a = new Array('x').concat(b,'y',c);
push(@a,1,2,3)             a.push(1,2,3)
pop(@a)                    a.pop() // returns undefined if empty
unshift(@a,4,5,6)          a.unshift(4,5,6) // array is now led by 4,5,6
shift(@a)                  a.shift()
@a[0..4]                   a.slice(0,4+1)
reverse(@a)                a.reverse()
@a = sort(@a);             a.sort();
@b = sort(@a);             b = a.slice(0); b.sort();
@a = sort {cf($a,$b)} @a;  a.sort(cf); // cf has typical compare semantics
scalar(@a)                 a.length // not a method, a property

Constructing

a = new Array("one","two","three");

concat

Combine multiple arrays and non-arrays into a single flat array.

a = new Array('B','C','D');
b = new Array('G','H','I');

c = new Array('A').concat(a,'E','F',b,'J','K');
// c contains 'A','B','C','D','E','F','G','H','I','J','K'

join

Make a string containing all elements in order.

a.join(separator);

slice

Copy out a segment of the array.

a.slice(beginIndex,postIndex);
a.slice(beginIndex,lastIndex+1);

If beginIndex is negative, it is treated as a.length + beginIndex. If postIndex is negative, it is treated as a.length + postIndex. If postIndex is before beginIndex, the result is an empty array.

Omitting postIndex copies to the end of the array. Specifying postIndex >= a.length has the same effect.

a.slice(0) returns a full copy of a.

splice

Delete and replace some elements of an array.

a.splice(beginIndex,count,replacement,...);
a = new Array(0,1,2,3,4,5);
a.splice(1,3,"yow","za");
// a is now 0,"yow","za",4,5

Number of replacement elements does not need to match number removed. If number removed exceeds number remaining, all remaining are removed. Arrays in replacement are not flattened.

reverse

Sx.

ar = a.reverse();