开发者

Using a generic prompt function to get data for several variables and change the prompt message each time

A bit of a lengthy title, but I couldn't think of any way to cut it down. What I want to do is see if I can make a prompt function that I can use multiple times to store information for multiple variables. The problem is I want the message in the prompt to change each time so the user knows what I'm asking for. I think there's some way I can pass a a line of text to the function so it knows what to tell the user. Here's roughly what I have so far:

function getNum()
{
 var userInput
 do
 {
  userInput = prompt([THIS IS WHERE I WANT THE TEXT TO CHANGE]) * 1;
 }while (isNaN(userInput));
 return userInput;
}

Any tips?开发者_如何学编程


does this work.

   function getNum(message)
    {
     var userInput
     do
     {
      userInput = prompt(message) * 1;
     }while (isNaN(userInput));
     return userInput;
    }


This will return an array of answers to each question defined in the prompts array.

function getNum() {
  var userInput = [];
  var prompts = ["Question1","Question2","Question3"];
  for( var i = 0; i < prompts.length; i++ ) {
    userInput[i] = prompt(prompts[i]);
  }
}

Edit: I don't think that's what you're asking for, though.


Well I've found out how do accomplish what I was trying to. Hopefully this will be helpful to anyone in a similar situation.

Here's the function:

function getNum(displayString)
{
    var userInput;
    do
    {
        userInput = prompt(displayString,"")*1;
    }while(isNaN(userInput));
    return userInput;
}

And here's how I passed a string:

Ex)

var userTable = getNum("The first number is the times table");

For some reason the javascript would never be able to execute unless I worded the parameter like this.

Display string is the string I pass to the function, and when I declare and initialize the variable "userTable", I call the function, passing the string in the brackets as the parameter. This is what would play the role of "displayString" in the function.


let lengthofArry = prompt("Talk length of arry");
let newarry = [];
let userdata = 0;
for (let i = 0; i< lengthofArry; i++)  {
  let userdata = prompt(`Enter Array value ${i+1} `);
    userdata = parseInt(userdata)
    newarry.push(userdata);
};
console.log(newarry);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜