【发布时间】:2016-12-26 21:39:39
【问题描述】:
我正在编写一个 AI 代码。它不工作。浏览器说:Uncaught ReferenceError: do is not defined。
var what = ["jokes", "cats", "news", "weather", "sport"];
function start() {
var do = what[Math.floor((Math.random() * what.length) + 1)];
}
start();
Document.write(do);
【问题讨论】:
-
了解 javascript 中的函数作用域(基本上函数内定义的变量仅在该函数内可见)
-
就像 mic4ael 所说,这是 Javascript 中“范围”的问题。 'do' 是在函数中定义的,因此在外部不可用。如果你在函数之外初始化了“do”,你就可以访问它。
-
"do" 是 JavaScript 保留字。我建议使用其他名称。
-
你应该声明变量外部函数和
what[Math.floor(Math.random() * what.length) + 1]这里+1总是返回空。试试what[Math.floor(Math.random() * what.length)]
标签: javascript function var