tags:

views:

34

answers:

2

how do i get the end key value for a javascript array?

i want to compare it with another value.

EDIT: and how do you declare a value directly with a declaration of an array. i have to use 2 lines for it.

var arrayname = new Array(); arrayname[] = 'value';

could one do that in one line?

+3  A: 

You can initialize an array at one go using:

var arrayname = [ 'value' ];

Accessing the last value uses:

arrayname[arrayname.length-1];

The previous assumes that the array has a length greater than zero. If the array can be empty you should check that length is greater than zero before trying to access the last element.

tvanfosson
+3  A: 

You can create arrays in one of many ways.

var foo = new Array();
foo[0] = 'a';
foo[1] = 'b';
foo[2] = 'c';

//is the same as:
var foo = new Array();
foo.push('a');
foo.push('b');
foo.push('c');

//is the same as:
var foo = [];
foo.push('a');
foo[1] = 'b';
foo[foo.length] = 'c';

//is the same as:
var foo = ['a','b','c'];

//is the same as:
var foo = 'a|b|c'.split('|');

Of course, if you only want to build an array to pass the array to another function, you can build it anonymously on the fly:

doSomething('param1', ['a','b','c'], 'param3');
scunliffe