0

I'm making a program that requires different parts in a variable the code goes like this

    var num=Math.round(Math.random()*5);
var a;
var a[0]="hi"
/*I've done this before, but remember it as a[num] */
var a[1]...
/*Many vars later*/
console.log(a[num])

this code always says that a[] does not work

3
  • Can you show us the extract error ? Commented Mar 30, 2016 at 21:35
  • @thangngoc89 I'm usinc Codecademy(a website that runs coding) and it says "Uncaught SyntaxError: Unexpected token [" Commented Mar 30, 2016 at 21:36
  • 2
    var a; You need to tell it's an array: var a = []; Commented Mar 30, 2016 at 21:37

2 Answers 2

2

You need to tell the compiler it's an array

var a = [];
a[0] = 'hi';
console.log(a[0]); // => hi
Sign up to request clarification or add additional context in comments.

1 Comment

i just realized it did. something doesnt work on my full code
1

Set this

var a;

to

var a = [];

for a declaration of an Array.


Please change this

var num=Math.round(Math.random()*5);

to

var num = Math.floor(Math.random() * 5); // for numbers from 0 to 4

because Math.round rounds depending up or down. Math.floor gets the integer part of a number.


var num = Math.floor(Math.random() * 5); // for numbers from 0 to 4
var a = [];
a[0] = "ha";
a[1] = "he";
a[2] = "hi";
a[3] = "ho";
a[4] = "hu";
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');
document.write(a[num]);

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.