The Now Platform® Washington DC release is live. Watch now!
Our young developer has just discovered that her boss has been keeping secrets from her. All this time in her (extensive) JavaScript programming experience, she's believed that arrays were places where you could store lists of like things. You could have an array of numbers, for example, or an array of strings. And certainly her boss never told her that you could use an array like a stack, or rotate the elements in it, or reverse their order, or any number of other nifty things.
This morning she discovered that arrays were cool. Who knew? And now she's raging...
The Array object is so cool that it's hard for your blogger to know where to start. I guess first we'll just clear up a common misconception: that arrays can only be used to store things of the same type. Consider this code:
var a = [152,'test',true,null,{test:'xxx',there:'yyy'}];
JSUtil.logObject(a);
Log Object
Array of 5 elements
[0]: number = 152
[1]: string = test
[2]: boolean = true
[3]: null = null
[4]: Object
there: string = yyy
test: string = xxx
var a = [];
a.push(55);
a.push(83);
a.push(29);
gs.log('Size: ' + a.length);
gs.log(a.pop());
gs.log(a.pop());
gs.log(a.pop());
gs.log('Size: ' + a.length);
gs.log(a.pop());
Size: 3
29
83
55
Size: 0
undefined
var a = [];
a.push(55);
a.push(83);
a.push(29);
gs.log('Size: ' + a.length);
gs.log(a.shift());
gs.log(a.shift());
gs.log(a.shift());
gs.log('Size: ' + a.length);
gs.log(a.shift());
Size: 3
55
83
29
Size: 0
undefined
var a = [55,83,29];
gs.log(a);
a.push(a.shift());
gs.log(a);
a.unshift(a.pop());
gs.log(a);
a.unshift(a.pop());
gs.log(a);
a.push(a.shift());
gs.log(a);
55,83,29
83,29,55
55,83,29
29,55,83
55,83,29
var a = [55,83,29];
gs.log(a);
a.reverse();
gs.log(a);
a.reverse();
gs.log(a);
55,83,29
29,83,55
55,83,29
var a = [55,83,29,76,14];
gs.log(a);
var b = a.slice(1,3);
gs.log(b);
b = a.slice(-2,1);
gs.log(b);
b = a.slice(-2,-1);
gs.log(b);
b = a.slice(-2);
gs.log(b);
55,83,29,76,14
83,29
76
76,14
var a = [55,83,29,76,14];
gs.log(a);
var b = a.splice(2, 0, 71, 72, 73);
gs.log(a + " : " + b);
b = a.splice(2, 3, [99,98]);
gs.log(a + " : " + b);
b = a.splice(-5, 3, [68,67,66]);
gs.log(a + " : " + b);
b = a.splice(1, 4, [51,52],53,[54,55]);
gs.log(a + " : " + b);
55,83,29,76,14
55,83,71,72,73,29,76,14 :
55,83,99,98,29,76,14 : 71,72,73
55,68,67,66,76,14 : 83,99,98,29
55,51,52,53,54,55 : 68,67,66,76,14
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.