【问题标题】:Why doesn't calling a function from an object work in this for loop?为什么从对象调用函数在这个 for 循环中不起作用?
【发布时间】:2014-12-01 12:06:13
【问题描述】:

编辑:问题已解决,我之前忘记为 riteg 对象输入输出。

好的,所以我很确定如何描述这个问题(这就是标题不好的原因),但是这个 for 循环:

function(){
            var out = 0;
            for(var i = 0;i<gameLists.listAllGen.length;i++){
                out += window[gameLists.listAllGen[i]].output();
            }
            return out/10000;
        },

根本不起作用。在控制台中,它说:TypeError: window[gameLists.listAllGen[i]].output is not a function

当我用 [0] 替换 [i] 时,它可以工作:

function(){
            var out = 0;
            for(var i = 0;i<gameLists.listAllGen.length;i++){
                out += window[gameLists.listAllGen[0]].output();
            }
            return out/10000;
        },

按预期返回并且没有错误。

如果需要的话,变量:

var gameLists = {
    listAllGen:['solarGen','riteg']
}

var solarGen = {
    name:"Solar Generator",
    count:0,
    genRate:0.25,
    price:410,
    output:
        function(){
            return this.count*this.genRate*10000;
        },

【问题讨论】:

  • 不,这不是打错字。字符串应该与 window 一起使用,例如 window[solarGen] 返回错误,但 window["solarGen"] 不会。
  • jsfiddle.net/9ad6kbfa 似乎确实有效。也许您以错误的顺序定义数据?
  • 我添加了分号,它现在似乎按预期工作(除了烦人的浮点数)。感谢您的帮助!
  • @Doge - riteg的定义在哪里?

标签: javascript arrays object for-loop


【解决方案1】:
gameLists.listAllGen[0] returns ->  solarGen

并且您的脚本中有solarGen,因此window[gameLists.listAllGen[0]].output() 指的是输出键,() 调用与键solarGen 关联的函数

但是gameLists.listAllGen[1]返回-> riteg

并且没有输出属性与 riteg 相关联,因此它和它所期望的 window[gameLists.listAllGen[1]]。有 riteg 以输出作为键 a 和与之关联的函数,但它无法找到。

因此你得到了错误

TypeError: window[gameLists.listAllGen[i]].output is not a function

因为没有同名的函数。

【讨论】:

  • 发布此问题后,我继续查看 riteg 对象并想“嘿,这需要一个输出函数”。我什至没有意识到我已经解决了这个问题,并最终错误地将问题归因于缺少分号(据我了解,这在 JavaScript 中不是严格必需的)。
猜你喜欢
  • 2023-01-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-13
  • 1970-01-01
  • 2019-09-27
  • 2019-06-28
  • 1970-01-01
相关资源
最近更新 更多