2
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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much for making it easyer
@StojanSpasic all those methods have links, just click on them.
2

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);

4 Comments

Neither of these actually do anything with the prompt()... FYI, I'm not the one that downvoted, I'm just making an observation.
@PatrickRoberts, what do you mean? What should we do with prompt()?
@PatrickRoberts, if you mean that i didn't pass any default content - the OP didn't say, that he needs it. But i have updated the answer with prompt's content
I meant you didn't assign it to anything... they're just a bunch of pointless prompts that don't actually store anything to memory.
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.