2016-08-19 150 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)});