我试着做一些转换语句,可以回答一些问题,我把它添加到其中。我希望答案以用户名结尾,所以如果输入提示"My name is Alex“,它将在"var username”中保存Alex;我希望"username“在定义"sendUserName”函数之前就具有该值。
<html>
<body>
<script>
var ask = prompt("Ask me anything >>").toLowerCase();
function write(x) {
document.write(x)
};
//Capitalize the first letter func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............
var question = ask.split(" ");
var date = new Date;
var userName;
//...............................
write(userName); // <------ here the issue , undefined !
if (question[0] === "what") {
switch (question[1]) {
case "time":
switch (question[2]) {
case "is":
switch (question[3]) {
case "it":
write(date);
break;
default:
};
break;
default:
};
break;
case "is":
switch (question[2]) {
case "your":
switch (question[3]) {
case "name":
write("Alex !");
break;
default:
};
break;
default:
};
break;
default:
write("unknown");
};
} else if (question[0] === "my") {
switch (question[1]) {
case "name":
switch (question[2]) {
case "is":
userName = capitalize(question[3]);;
alert("Your name is saved, " + userName);
function sendUserName() {
return userName;
}
break;
default:
};
break;
default:
};
};
sendUserName();
write(userName); // <------- it's work here
</script>
</body>
</html>发布于 2016-03-21 11:00:30
在您的代码中,第一个write(userName)在遍历if- and语句和开关之前被调用。解决方法(在我看来也会改进结构)是定义一个新函数processor(input)并将所有逻辑放在那里,然后在调用write()之前以用户输入作为参数调用该函数。见下面的代码:
var ask = prompt("Ask me anything >>").toLowerCase();
function write(x) { document.write(x) };
//Capitalize the first letter func :
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
//..............
var input = ask.split(" ");
var date = new Date;
var userName;
//...............................
processor(question); // the processor function is called with the value of variable question
write(userName); // <------ Now it is defined even here
function processor(input) {
if (input[0] === "what") {
switch (input[1]) {
case "time":
switch (input[2]) {
case "is":
switch (input[3]) {
case "it":
write(date);
break;
default:
};
break;
default:
};
break;
case "is":
switch (input[2]) {
case "your":
switch (input[3]) {
case "name":
write("Alex !");
break;
default:
};
break;
default:
};
break;
default:
write("unknown");
};
} else if (input[0] === "my") {
switch (input[1]) {
case "name":
switch (input[2]) {
case "is":
userName = capitalize(input[3]);;
alert("Your name is saved, " + userName);
break;
default:
};
break;
default:
};
};
}
function sendUserName() {
return userName;
}
sendUserName();我没碰过你的密码。我刚刚在函数processor(input)中丢弃了所有的逻辑,并将函数sendUserName()从函数中删除,使其成为全局的。当然,如果您需要,可以将它放回原处,但请注意,如果您没有到达定义该函数的逻辑部分,则可能会通过调用该函数而出错。
https://stackoverflow.com/questions/36128866
复制相似问题