1

I have the following code:

var items = [item1, item2, item3];

var index = Math.random() * items.length;

I expect the statement

items[index]

to return a random item from my array, however it always returns undefined. How do I get the item indexed by the index variable?

1
  • The Math.random() function returns a floating-point, pseudo-random number in the range 0–1 (inclusive of 0, but not 1) Commented Dec 13, 2018 at 22:26

3 Answers 3

4

You need an integer value index, because an Array is organized by positive integer values.

If you use a not integer value, the value is converted to a string (this applies to the integer value, too) and used as property accessor. An in this case, for example 1.22, the value does not exist in the array and you get undefined.

BTW, arrays are objects in Javascript, so all values could be used as key for the array.

var items = ['item1', 'item2', 'item3'];
var index = Math.floor(Math.random() * items.length);

console.log(items[index]);

Sign up to request clarification or add additional context in comments.

Comments

2

You should floor the number befaore using it as subscript:

var index = Math.floor(Math.random() * items.length);

That way you'll get integer values for index and not floating ones.

1 Comment

I forgot to get an integer, my bad. Thanks
0

Use Math.round() to round up the index

var index = Math.round(Math.random() * (items.length - 1));

Otherwise it could point to something like 2.3 which isn't incöuded in the array

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.