1

I'm not sure how I would do this in Javascript. I want to create an array that would contain any number of error messages from my form.

I read on websites that you define the key for that array when adding new entries.

// Javascript
var messages = new Array();
messages[0] = 'Message 1';

How can I add entries into my array using a similar method I normally do in PHP

// PHP    
$messages = array();
$messages[] = 'Message 1'; // automatically assigned key 0
$messages[] = 'Message 2'; // automatically assigned key 1

Is it possible to emulate that in Javascript? I don't want to have to define the number of entries in my array as it can vary.

Thanks for helping me out on this very basic js question. -Lyon

6
  • 1
    @Lyon: This is one of those questions that can be answered by googling their title and reading the first result. Commented Apr 17, 2010 at 9:27
  • 1
    @Tomalak: And the goal according to Joel is that the question on stackoverflow is that first result google returns and the best answer you can find on the web. Commented Apr 17, 2010 at 10:25
  • @Volker: Ahhhh, that's a lame excuse and you know it. Even if the first result and best possible answer would be a Stack Overflow page... when people are not googling for an answer before asking away happily that wouldn't make much of a difference, would it. Apart from that I don't think it's SO's misssion to re-create all the programming knowledge in the world (because it's not "real" when it is not on SO and reading the spec is lame, or what?). Commented Apr 17, 2010 at 12:04
  • @Tomalak: There certainly discussion about that on meta.stackoverflow.com e.g. meta.stackexchange.com/questions/4448/… Commented Apr 17, 2010 at 14:38
  • @Tomalak with all due respect, i did my fair share of googling and checking out javascript array resources. The fact that I was searching for an answer similar to php's solution probably led to me never encountering the .push() method. With SO, I am able to present what I know in PHP, and ask the SO community on how best to do the same in Javascript. Google won't tell me that. Commented Apr 19, 2010 at 5:31

2 Answers 2

3
var messages = new Array();
messages.push('Message 1');
messages.push('Message 2');
Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it by 7 seconds. ;) +1
For the definition in ecmascript 3rd edition see mozilla.org/js/language/E262-3.pdf @ "15.4.4.7 Array.prototype.push"
2
messages.push('Message n');

that should do the trick :)

reference here

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.