Reputation: 21
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
Reputation: 16384
Just create an array with prompt
s 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
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
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