0

I have five user variables with different names. I'd like them to end up in an array, and am wondering if I can do the assignment to multiple array indices in a single line. Currently, if I do this

var users = {user5k, user10k, user15k, user20k, user25k};

I can't index it later (says users[0] is undefined). So I want the indices built in to the assignment. Something along these lines:

var users = {};
users[0:4] = {user5k, user10k, user15k, user20k, user25k};

This doesn't seem possible in JavaScript, meaning I have to do this:

var users = {};
users[0] = user5k;
users[1] = user10;
// ... et cetera

Is there a way to accomplish the first solution?

data princess
  • 1,130
  • 1
  • 23
  • 42
  • 6
    `{}` is for objects, `[]` is for arrays. – Barmar Sep 05 '17 at 17:12
  • 1
    Yes, you are defining an `object` when you use `{}`. For an array which you can index, use `[]`. – Ari Seyhun Sep 05 '17 at 17:14
  • 2
    In case it's not clear, you need `var users = [user5k, user10k, user15k, user20k, user25k];` –  Sep 05 '17 at 17:14
  • 1
    I'd go back to your JS tutorial/intro and carefully re-read the part about basic data types, including objects and arrays. –  Sep 05 '17 at 17:16

1 Answers1

0

When you use {} you're creating an object, not an array. Use [] for arrays.

var users = [user5k, user10k, user15k, user20k, user25k];

If you want to replace part of an array that already exists, you can use Array.prototype.splice()

var users = [];
users.splice(0, 4, [user5k, user10k, user15k, user20k, user25k]);
Barmar
  • 741,623
  • 53
  • 500
  • 612