0

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?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
yjs
  • 692
  • 3
  • 11

1 Answers1

1

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());
baao
  • 71,625
  • 17
  • 143
  • 203