-4

Am I allowed to do this in JavaScript?

var 1 = "me";
var 2 = "you";
var 3 = "we";

If not, what's the work around it?

My goal is to create a game where a random number is generated then I answer what that number represents.

  • 2
    This question appears to be off-topic because it is about extremely basic aspects of JavaScript, namely what is a valid identifier. –  Apr 30 '14 at 17:14
  • 2
    possible duplicate of [Valid Characters for JavaScript Variable Names](http://stackoverflow.com/questions/1661197/valid-characters-for-javascript-variable-names) – Sterling Archer Apr 30 '14 at 17:14
  • 1
    @RUJordan - isn't the question really -- how can I define values for numbers (with an answer of dictionary or array) not what valid characters are for variable names? – Hogan Apr 30 '14 at 17:18
  • 1
    It's an implicit question. He asked if those were allowed variable names. Not to mention it shows no attempt, and it's very basic stuff. So it should be closed. – Sterling Archer Apr 30 '14 at 17:20
  • Although this is a naive question, how do you expect a beginner to ask about arrays if they don't even know arrays exist? – twiz Apr 30 '14 at 17:28
  • Maybe not ask about arrays, but at least do a simple search before asking. RUJordan gave a pretty good link and I don't think he got it from his recurrent bookmarks. – Nunser Apr 30 '14 at 17:47

4 Answers4

3

I think you want an array:

var answers = ["","me","you","we"];

then:

answers[1]

has this value:

"me"
admdrew
  • 3,790
  • 4
  • 27
  • 39
Hogan
  • 69,564
  • 10
  • 76
  • 117
2

Use an object:

var obj = {1: "me",
           2: "you",
           3: "we"};

Then when you generate the random number you can look up the associated value using obj[number]. Of course if the numbers are always in sequence you could use an array instead, you would just need a dummy value at the beginning since array indexing starts at 0, so doing something like var arr = [null, "me", "you", "we"]; would work the same way.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

No, you can't. The workaround is to start the variable name with a letter:

var a1 = "me";
var a2 = "you";
var a3 = "we";
La-comadreja
  • 5,627
  • 11
  • 36
  • 64
1

you should use array

var answers = ["","me","you","us"];



  answers[1] returns me
      answers[2] returns you
       answers[3] returns us 

or use a letter as prefix

like

var b1 = "me";
var b2 = "you";
var b3 = "we";
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49