【问题标题】:javascript: Uncaught TypeError: Cannot read property 'X' of undefinedjavascript:未捕获的类型错误:无法读取未定义的属性“X”
【发布时间】:2021-01-16 07:52:54
【问题描述】:

我想知道为什么这个函数会返回这个错误:

未捕获的 ReferenceError:未定义 capasPlay 在 funPlay.handleFunPlay

funPlay.prototype.handleFunPlay = function handleFunPlay() {
        
        capasPlay = [capa4_48R, capa4_49R, capa4_50R, capa4_51R, capa4_52R, capa4_53R, capa4_54R, capa4_55R, capa4_56R];

        
        var index;
        
        for (index=0; index <= capasPlay.leght; index++){
            
            window.setTimeout(function(){capasPlay[index].setVisible(false)}, 1000);
        }
    };
    return funPlay;

数组是由这样的变量组成的:

var capa4_48R = new TileLayer({
                source: new TileWMS({
                    url: 'http://localhost:8080/geoserver/wms',
                    params: { 'LAYERS': 'earth:4_48R', 'TILED': true },
                    serverType: 'geoserver',
                })
});

非常感谢!

【问题讨论】:

  • 您发布的代码中没有任何地方尝试读取名为X 的属性。请提供minimal reproducible example 证明您遇到的问题。至少错误可能来自setVisible方法,所以也许向我们展示一下,
  • 对不起,伙计。你说的对。错误是:Uncaught ReferenceError: capasPlay is not defined at funPlay.handleFunPlay
  • 错误很明显,你在哪里定义capasPlay?
  • 这里是数组的定义:
  • capasPlay = [capa4_48R, capa4_49R, capa4_50R, capa4_51R, capa4_52R, capa4_53R, capa4_54R, capa4_55R, capa4_56R];

标签: javascript arrays typeerror


【解决方案1】:

如果你没有使用 vanilla Javascript,你需要明确定义 带有varconstlet 的变量。

const capasPlay = [ ... ]

【讨论】:

  • 我已将其定义为 const 但发生了同样的错误。也许“setTimeout”函数不适用于迭代。也许它没有被认为是这样工作的。不确定。谢谢朋友
【解决方案2】:

我假设你用“X”替换了你实际调用的任何属性?

我发现您的循环存在问题,该问题会导致未定义的属性错误。当setTimeout 触发的函数被调用时,index 将超出范围。要解决此问题,您需要为循环的每次迭代保存当前索引的副本。

for (index=0; index <= capasPlay.leght; index++){
    const i = index;
    window.setTimeout(function(){capasPlay[i].setVisible(false)}, 1000);
}

更新

正如setTimeout in for-loop does not print consecutive values 所建议的,有一个更好的解决方案,我不知道。

for (let index=0; index <= capasPlay.leght; index++){
    window.setTimeout(function(){capasPlay[index].setVisible(false)}, 1000);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 2016-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    相关资源
    最近更新 更多