0

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?

1
  • 2
    You're asking two different questions. Please move the second question to another question. Dec 25, 2009 at 16:53

2 Answers 2

3

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');
3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.