Get the element of an array that has an index given by a variable in JavaScript

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?

Upvotes: 1

Views: 411

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

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]);

Upvotes: 4

ibrahim mahrir
ibrahim mahrir

Reputation: 31682

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.

Upvotes: 2

user7838288
user7838288

Reputation:

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

Upvotes: 0

Related Questions