I
I
Ingerniated2018-02-07 02:11:37
JavaScript
Ingerniated, 2018-02-07 02:11:37

How to get the name of a variable in an array?

Goodnight!
There are variables in the array, how to get their name as a string?

var x = 10;
var y = 3;
var arr = [x,y];

How, when requesting to, to arrget a string "x"and "y"?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-07
@Ingernirated

No way. They are not in the array. There inside the values ​​of x and y at the time of assignment:

{
  0: 10,
  1: 3,
  length: 2,
  __proto__: Array(0)
}

For your task, it is better for you to add data to an object:
var x = 10;
var y = 3;
var obj = { x: x, y: y };

var keys = Object.keys(obj);

console.log(keys);
// => [ 'x', 'y']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question