Javascript 为什么';从对象调用函数不能在这个for循环中工作吗?
编辑:问题解决了,我忘了把riteg对象的输出放在前面 好的,我很确定如何描述这个问题(这就是为什么标题不好),但是这个for循环:Javascript 为什么';从对象调用函数不能在这个for循环中工作吗?,javascript,arrays,object,for-loop,Javascript,Arrays,Object,For Loop,编辑:问题解决了,我忘了把riteg对象的输出放在前面 好的,我很确定如何描述这个问题(这就是为什么标题不好),但是这个for循环: function(){ var out = 0; for(var i = 0;i<gameLists.listAllGen.length;i++){ out += window[gameLists.listAllGen[i]].output(); }
function(){
var out = 0;
for(var i = 0;i<gameLists.listAllGen.length;i++){
out += window[gameLists.listAllGen[i]].output();
}
return out/10000;
},
按预期返回,没有错误
变量(如果需要):
var gameLists = {
listAllGen:['solarGen','riteg']
}
及
您的脚本中有solarGen
,因此窗口[GameList.listAllGen[0]]。output()
引用输出键,()
调用与该键关联的函数solarGen
但是gameLists.listAllGen[1]
return->riteg
并且没有任何输出属性与riteg关联,因此它和它期望的窗口[gameLists.listAllGen[1]
。有一个riteg,它的输出是一个键a和一个与其关联的函数,但它无法找到它
因此,您得到了错误
TypeError: window[gameLists.listAllGen[i]].output is not a function
因为没有使用该名称的函数。这是否有帮助:不,这不是错误输入。字符串应该与window一起使用,例如window[solarGen]返回错误,但window[“solarGen”]不返回错误。看起来确实有效。也许您定义数据的顺序不对?我添加了分号,现在它似乎可以正常工作了(除了恼人的浮点数据)。谢谢你的帮助@Doge-riteg的定义在哪里?在我发布了这个问题后,我继续看了一下riteg对象,然后想“嘿,这需要一个输出函数”。我甚至没有意识到我已经解决了这个问题,结果错误地将问题归因于缺少分号(据我所知,分号在JavaScript中并不是绝对必要的)。
var solarGen = {
name:"Solar Generator",
count:0,
genRate:0.25,
price:410,
output:
function(){
return this.count*this.genRate*10000;
},
gameLists.listAllGen[0] returns -> solarGen
TypeError: window[gameLists.listAllGen[i]].output is not a function