【问题标题】:Variable not defined - javascript [duplicate]未定义变量 - javascript [重复]
【发布时间】: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


【解决方案1】:

你做的变量超出范围

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

【讨论】:

    【解决方案2】:

    do 在这里是一个变量而不是一个函数。

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

    【讨论】:

    • 这将如何工作?很确定那是无效的 JavaScript:do = function() = {?而document.write(do) 会写成function() {...},而不是调用函数的结果。
    • @MikeMcCaughan:一些错别字......和无效......改变......
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      var what = ["jokes", "cats", "news", "weather", "sport"];
      var do;
      function start() {
      
          do = what[Math.floor((Math.random() * what.length) + 1)];
      }
      start();
      Document.write(do);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-04-25
        • 2011-07-06
        • 2022-01-03
        • 2013-04-28
        • 2019-09-29
        • 2014-12-05
        • 1970-01-01
        • 2016-06-16
        相关资源
        最近更新 更多