0

lets say I have an array: it could look like this at one time:

var fruit = [apple,orange];

or like this:

var fruit = [orange, apple];

These are global variables, equaling some value - orange and apple How could I get the name of the variable at index 0 - (fruit[0]) of fruit as a string?

Thanks

Rabbid76
  • 202,892
  • 27
  • 131
  • 174

2 Answers2

1

It depends where the code is running.

If these are in a function you can get them by calling .toString() on the function, like this:

const orange = "s";
const apple = "t";

function getVars() {
 var fruit = [orange, apple];
}

console.log(getVars.toString());

Output:

function getVars() {
    var fruit = [orange, apple];
}

Then you do some text processing and you have the variable names.

Why do you want to do this, out of curiosity?

Josh Wulf
  • 4,727
  • 2
  • 20
  • 34
  • 1
    I am making an "image loading function". The image data is in an object inside of another. If I have 3 images, there are 3 objects inside of the "images" object. I have a function that takes a paremeter "image" and checks whether to see the input matches any of the object names in my image array. If so, it sets that image to the this.image of the function. Then I can do whatever thing with the image using the function. sry if am not clear, my mom is telling me to eat luch!:) – Oyster_Bucket Feb 22 '20 at 19:55
  • If they are objects, that is different to arrays. Do you have some representative code of the objects you are working with? If you can put that in, or link to it, we can do a better job of helping you. – Josh Wulf Feb 22 '20 at 19:59
  • 1
    Thanks a lot. I am actually making it instead on khan academy for the fun of it. using their platform, a was able to make a "hack" that worked. Here is the link just for the part that gets the variable name: https://www.khanacademy.org/computer-programming/get-name-of-variable/5921008813096960 – Oyster_Bucket Feb 22 '20 at 20:02
  • Very good! All variables are keys on the global object. Smart! – Josh Wulf Feb 22 '20 at 20:05
  • Its very easy to code stuff on KA. You should try messing around and see what you come up with. I've made some quite good small games – Oyster_Bucket Feb 22 '20 at 20:09
1

To elaborate on @evolutionxbox comments – you'd need to use an object such as:

const orange = 'An orange'
const apple = 'An apple'

const fruit = {
  orange,
  apple
}

console.log(Object.keys(fruit)) // [ 'orange', 'apple' ]
console.log(Object.keys(fruit)[0]) // 'orange'
console.log(fruit.apple) // 'An apple'

Andy Mardell
  • 1,132
  • 8
  • 13