javascript 控制台日志不打印函数中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15694273/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Console log not printing variable from function
提问by oxxi
Trying to print the variable 'randomWord' to console.log, but chrome says it is not defined. It looks like it's defined to me. Why won't it print to the console.log?
试图将变量 'randomWord' 打印到 console.log,但 chrome 说它没有定义。看起来它是给我定义的。为什么它不会打印到console.log?
function strt(){
//get random word from words[] array
var randomWord = words[Math.floor(Math.random()* words.length)];
var wordLength = randomWord.length;
//create a blank boxes or div elements for holding each letter of
// selected random word
for(i = 0 ; i< wordLength; i++){
var divTag = document.createElement("div");
divTag.id = "div" + i;
divTag.className = 'wordy';
//divTag.innerHTML = randomWord[i];
hangManDiv.appendChild(divTag);
};// end for loop
//disable start button
document.getElementsByName("startB")[0].disabled = true;
return randomWord;
}//end strt()
console.log(randomWord);
回答by JCOC611
The variable randomWord
is out of the scope. You define the variable inside a function, and then call it outsideof it.
变量randomWord
超出范围。您在函数内部定义变量,然后在函数外部调用它。
You should either define the variable out of the function or call it inside of it:
您应该在函数外定义变量或在函数内部调用它:
function strt(){
var randomWord;
...
console.log(randomWord);
return randomWord;
}//end strt()
Or
或者
var randomWord;
function strt(){
...
return randomWord;
}//end strt()
strt(); // Call the function
console.log(randomWord);
For the latter, consider that randomWord
won't have changed when JS executes the console log function; therefore, it will be null. In other words, you must call the function before you log it.
对于后者,考虑到randomWord
JS 执行控制台日志功能时不会发生变化;因此,它将为空。换句话说,您必须在记录之前调用该函数。