控制台日志不能从函数中打印变量

编程入门 行业动态 更新时间:2024-10-24 20:16:10
本文介绍了控制台日志不能从函数中打印变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尝试将变量'randomWord'打印到console.log,但chrome表示未定义。 它看起来像是我定义的。为什么不打印到console.log?

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?

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);

推荐答案

变量 randomWord 超出了范围。您在函数内定义变量,然后将其命名为 outside 。

The variable randomWord is out of the scope. You define the variable inside a function, and then call it outside of it.

您应该从函数中定义变量或在函数内部调用它:

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()

var randomWord; function strt(){ ... return randomWord; }//end strt() strt(); // Call the function console.log(randomWord);

对于后者,请考虑 randomWord 赢了当JS执行控制台日志功能时,它已经改变了;因此,它将为空。换句话说,您必须在记录之前调用该函数。

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.

更多推荐

控制台日志不能从函数中打印变量

本文发布于:2023-11-28 09:04:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641779.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   变量   函数   日志

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!