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

时间:2015-08-18 22:45:37

标签: javascript function loops

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()
}

我正努力能够不断回答问题并让他们每次都改变。但是当我运行它时,每个提示都说同样的话:“问我一些事情。”请帮我找出我的逻辑错误。

1 个答案:

答案 0 :(得分:0)

这看起来像JavaScript,所以我将使用它。您的源代码存在一些问题。

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

下面我在JavaScript中提供了一个修改示例,用于更改prompt()显示的字符串。这使用全局变量two,该变量由函数ask()修改,具体取决于参数中指定的数字。 two字符串的值被修改为新字符串。

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

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

有关prompt()功能的信息,请参阅此页面JavaScript Popup Boxes,其中讨论了三种类型的弹出窗口或框,包括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>