Search code examples
javascriptarraysloopsprompt

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?


Solution

  • 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.