gpt4 book ai didi

javascript - 如何访问变量而不是重新声明它?或者这样做的另一种选择是什么?

转载 作者:行者123 更新时间:2023-11-28 13:55:12 28 4
gpt4 key购买 nike

如何修复 JSBin 中出现的这些错误?杰士宾 http://jsbin.com/ebizaj/edit#javascript,html我收到这些错误。

1.Line 6: var name = prompt("What is your name?", ""); --- 'name' is already defined.
2.Line 12: var PromptAnswer = prompt("So, " + name + " do you play Soccer?", ""); --- 'PromptAnswer' is already defined.
3.Line 35: var PromptAnswer3 = prompt("Well, what sports do you like to play?", ""); --- 'PromptAnswer3' is already defined.

我该怎么办?如果我尝试调用变量 PromptAnswer3,它不会执行任何操作。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Javascript Activity</title>
<script type="text/javascript">
function InitAll()
{
var name = prompt("What is your name?", "");
while (name == null | name == "") {
alert("You didn't answer! :D");
var name = prompt("What is your name?", "");
}
alert("Hello, " + name + " this is a little Javascript Activity!");
var PromptAnswer = prompt("So, " + name + " do you play Soccer?", "");
while (PromptAnswer == null | PromptAnswer == "") {
alert("You didn't answer, please try again.");
var PromptAnswer = prompt("So, " + name + " do you play Soccer?", "");
}

else if (PromptAnswer.match(/^(yes|yeah)!?$/i))
{
alert("Cool, that's awesome, i play Soccer too!");
var PromptAnswer2 = prompt("Well, even some people play Soccer and don't like it, do you like soccer?", "");
if (PromptAnswer2.match(/^(yes|yeah)!?$/i))
{
alert("Yeah, its pretty fun.");
}
else
{
alert("Well, that's really too bad, but i guess if you don't like it, you dont like it. :D");
}
}


else {
var PromptAnswer3 = prompt("Well, what sports do you like to play?", "");
while (PromptAnswer3 == null | PromptAnswer3 == "")
{
alert("You didn't answer");
var PromptAnswer3 = prompt("Well, what sports do you like to play?", "");
}
if (PromptAnswer3.match(/^(yes|yeah)!?$/i))
{
alert("Haha yeah, football is pretty awesome, even though i'm a Javascript Script, my Creator can throw football pretty well. :D");
}
else
{
alert(PromptAnswer3 + " is pretty cool.");
}
}
}
</script>
</head>
<body onload="InitAll()">
<noscript>
<p>Sorry, you do not have Javascript Enabled for this Activity.</p>
</noscript>
</body>

最佳答案

您可以在为变量赋值之前声明该变量。例如,不要写

var name = prompt("What is your name?", "");
while (name === null | name === "") {
alert("You didn't answer! :D");
var name = prompt("What is your name?", "");
}

你可以写

var name;
name = prompt("What is your name?", "");
while (name === null | name === "") {
alert("You didn't answer! :D");
name = prompt("What is your name?", "");
}

关于javascript - 如何访问变量而不是重新声明它?或者这样做的另一种选择是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8380808/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com