Stojan Spasic
Stojan Spasic

Reputation: 21

Multiple prompts in array with variable, is it possible?

var arr[2];
  for(i=0; i<arr.length; i++) {
  arr[i] = prompt() * 1;
}

But i was wondering you can do like var arr = [x,y,z] = [1,2,3]; can you do a loop for "x, y, z" with a prompt?

Upvotes: 2

Views: 395

Answers (3)

P.S.
P.S.

Reputation: 16384

Just create an array with prompts and assign it to variables:

var prompts = [
  prompt('0', '0'),
  prompt('1', '1'),
  prompt('2', '2'),
];
var [x, y, z] = prompts;
console.log(x, y, z);

Upvotes: 2

Patrick Roberts
Patrick Roberts

Reputation: 51936

You could also do this by using the Array() constructor and Array#map(). The Array#fill() is necessary in order to let map iterate through the whole array:

var [x, y, z] = Array(3).fill().map(prompt).map(Number)

console.log(x, y, z)

This approach uses the destructuring assignment syntax.

Upvotes: 2

Namaskar
Namaskar

Reputation: 2119

You cannot store variable references in an array, you could store the variables in an object, however:

var x;
var y;
var z;
var arr = {
  x,
  y,
  z
};
for (key in arr) {
  arr[key] = prompt() * 1;
}
console.log(arr);

Upvotes: 0

Related Questions