yjs yjs - 28 days ago 19
Javascript Question

Want to create a dynamic array from javascript prompt

Am trying to develop stepwise like below:


  1. Ask user to enter a array name using
    prompt()

  2. Prompt user to enter total size of array.

  3. Prompt user to enter each values...till it satisfies total size in step 2.

  4. Build array and display in page or console.-



Steps 2, 3 & 4 was done, and got end product.
But am not sure how to build step 1.

arrayName = prompt('');
arrayLength = prompt('');
for(var i=0; i<10; i++) {
arrayItems = prompt('');
arrayName[i] = arrayItems;
}
console.log(arrayName);
}


How to make
arrayName
appear as an array? Currently its returning only variable from prompt. I need
arrayName
variable input to be an array.

eg. If user input for first prompt be
"xyz"
, then
arrayName
will be
xyz
.
So that I can call
xyz[i]
. Is it possible to do that way. If yes, how could be?

Answer

I'd build an object and assign the values accordingly. That way you can simply use bracket notation to create the name

function build() {
  this._arrayName = prompt("name");
  this[this._arrayName] = [];
  this.arrayLength = prompt("length");
  for (var i = 0; i < this.arrayLength; i++) {
    this[this._arrayName].push(prompt("item"));
  }
  return this[this._arrayName];
}

console.log(build());