0

If you want to create an array and assign individual values to each item within that array, is this done by declaring the array and then declaring each individual variable within the array separately? :

let animals = [
  "cat",
  "dog"
  ];

let cat = "kitty";
let dog = "doggy";

If this is the correct method, then how would you call an item from the array using, for example, animals[Math.floor(Math.random() * animals.length)] but get the value of the individual variable (e.g. "kitty") and not just the variable name (cat)?

TomCo
  • 1
  • 1

2 Answers2

0

I doubt that this is a good way of doing what you actually want to do but if you have an array of strings and these strings represent a key in an object you can do the following:

const someObject = {
  cat : "kitty",
  dog : "doggy"
};
const keys = ["cat","dog"];
console.log(
  someObject[keys[Math.floor(Math.random()*keys.length)]]
)
HMR
  • 37,593
  • 24
  • 91
  • 160
0

As stated in my comment, you would want to store these in an object. JavaScript objects work with key/value pairs, so each key on the left needs a corresponding value.

let animals = {
  cat: "kitty",
  dog: "doggy",
  horse: "horsey"
}

let animalNames = Object.values(animals)

console.log("Random animal: " + (animalNames[Math.floor(Math.random() * animalNames.length)]))
console.log(animals.cat)
console.log(animals.dog)
console.log(animals.horse)
James Whiteley
  • 3,363
  • 1
  • 19
  • 46
  • Please see [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) and [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str May 03 '18 at 11:19