2016-08-19 171 views
0

我正在编写一个AI。它不工作。浏览器说:Uncaught ReferenceError:do没有定义。变量未定义 - javascript

var what = ["jokes", "cats", "news", "weather", "sport"]; 

function start() { 

    var do = what[Math.floor((Math.random() * what.length) + 1)]; 
} 
start(); 
Document.write(do); 
+2

阅读有关JavaScript函数范围(基本上变量中定义的变量只在该函数内部可见) – mic4ael

+0

像mic4ael所说,这是Javascript中“范围”的问题。 'do'是在一个函数中定义的,因此在外面不可用。如果你在函数之外初始化'做',你将可以访问它。 –

+0

http://stackoverflow.com/documentation/javascript/480/scope#t=201608182147440316607 –

回答

0
var what = ["jokes", "cats", "news", "weather", "sport"]; 
var do; 
function start() { 

    do = what[Math.floor((Math.random() * what.length) + 1)]; 
} 
start(); 
Document.write(do); 
0

做的是这里的变数,而不是功能。

var do = what[Math.floor((Math.random() * what.length) + 1)]; 

创建一个do函数,你会这样做。

var what = ["jokes", "cats", "news", "weather", "sport"]; 
var do; 
function start() {  
    do = function(){ return what[Math.floor((Math.random() * what.length) + 1)]}; 
} 
start(); 
Document.write(do()); 
+0

这将如何工作?很确定这是你得到的无效JavaScript:'do = function()= {'?而'document.write(do)'会写'function(){...}',而不是调用该函数的结果。 –

+0

@MikeMcCaughan:一些错别字......和残疾人..改变了...... – Thalaivar

0

Do只存在于你的函数中。阅读关于功能范围:)试试这个:

var what = ["jokes", "cats", "news", "weather", "sport"]; 
var do = undefined; 
function start() { 
    do = what[Math.floor((Math.random() * what.length) + 1)]; 
} 
start(); 
Document.write(do); 
0

你做的变量超出范围

var what = ["jokes", "cats", "news", "weather", "sport"]; 

function start() { 

    var do = what[Math.floor((Math.random() * what.length) + 1)]; 
} 
start(); 
Document.write(do); 

您需要更改您的代码

var what = ["jokes", "cats", "news", "weather", "sport"]; 

function start(callback) { 

    var do = what[Math.floor((Math.random() * what.length) + 1)]; 
    callback(do); 
} 
start(function(val) {document.write(val)});