更改for循环中prompt()函数中使用的字符串不会更改显示的提示符

changing strings used in prompt() function in for loop is not changing displayed prompt

本文关键字:字符串 提示符 显示 prompt 循环 for 更改 函数      更新时间:2023-09-26
var two = "Ask me something!"
function ask(one, two) {
    if (one == "hi") {
        two = "Hello how are you!"
    } else if (user == "How old are       you?") {
        two = "I am 800 years old"
    }
};
for (i=0;i<10;i++) {
      prompt(two);
      ask()
}

我试着能够继续回答问题,让他们每次都改变。但是当我运行它时,每个提示都说同样的话:"问我一些问题。"请帮我找出我的逻辑错误

这看起来像JavaScript,所以我要用它工作。你的源代码有几个问题。

首先,你的函数ask()需要在循环中调用时提供一些参数。

下面我提供了一个JavaScript修改的例子,它改变了prompt()显示的字符串。它使用一个全局变量two,该变量由函数ask()根据参数中指定的数量进行修改。将two的字符串值修改为新的字符串。

这是使用switch()语句,如果指定的值在1(1)到10(10)的范围内,则two的值将更改为指定的新字符串。如果ask()参数中指定的值不在范围内,则不会更改two的值。

您可以修改case语句,其中对全局变量two进行赋值,以改变实际提示或prompt()框中显示的内容。

有关prompt()函数的信息,请参阅本页,JavaScript弹出框,其中讨论了三种类型的弹出窗口或框,包括prompt()框。

您可能需要如下内容:

<script>
// create a global variable we are going to use for our prompts.
// each time the function ask() is called, the variable will be modified.
var two = "Ask me something!"
// the function ask() which takes an argument and changes the global variable
// two to a different string.  the function takes two arguments.
// the first argument is an index value from 1 to 10 inclusive.
// the second argument is a string to append to the selected prompt.
function ask(one,answer) 
{
    switch (one) {
        case 1:
            two = " 1. Hello how are you! " + answer;
            break;
        case 2:
            two = " 2. Hello how are you! " + answer;
            break;
        case 3:
            two = " 3. Hello how are you! " + answer;
            break;
        case 4:
            two = " 4. Hello how are you! " + answer;
            break;
        case 5:
            two = " 5. Hello how are you! " + answer;
            break;
        case 6:
            two = " 6. Hello how are you! " + answer;
            break;
        case 7:
            two = " 7. Hello how are you! " + answer;
            break;
        case 8:
            two = " 8. Hello how are you! " + answer;
            break;
        case 9:
            two = " 9. Hello how are you! " + answer;
            break;
        case 10:
            two = "10. Hello how are you! " + answer;
            break;
    }
};
// run a loop providing a prompt and then changing the global variable two
// to provide a different prompt. we provide a default string, the second
// argument that includes the value of the index variable used in the loop.
//
// we are taking what ever the user enters and appends that string to the
// next prompt string.
//
// if the user presses the Cancel button on the prompt box then we will get
// a value of null and so we will just break out of the loop.
for (i = 1; i <= 10; i++) {
      var answer = prompt(two, "stuff " + i);
      if (answer == null) break;
      ask(i, answer)
}
</script>