简体   繁体   English

为什么在使用window变量查找索引时出现错误?

[英]Why I'm getting an error when looking for an index using window variable?

This is very strange, I'm trying to use a variable which I define as is: 这很奇怪,我试图使用一个按原样定义的变量:

window.params['variable'] = { ... };

In the function I'm using I have this: 在我正在使用的函数中,我有这个:

function q()
{
 ...
 // for example
 return new Chart( canvas, window.params['variable'] );
 ...
}

When I execute this I get the error: Uncaught TypeError: Cannot read property 'variable' of undefined 当我执行此操作时,我得到一个错误: Uncaught TypeError: Cannot read property 'variable' of undefined

But, incredible (for me), when I define params as: 但是,当我将参数定义为:

window.params = { ... }

The error disappear, and the function runs fine! 错误消失,功能正常运行! why? 为什么?

(Obviusly I replace the window.params['variable'] by window.params first, but I believe that this is equivalent) (Obviusly我更换window.params['variable']通过window.params第一,但我认为,这是等效)

Thanks. 谢谢。

You need to define params first before adding properties to params . 您需要定义params第一属性添加到之前params So the right way to do it is 所以正确的方法是

window.params = {};
window.params['variable'] = { };

or 要么

window.params = {
  'variable' : {}
};

and then 接着

function q(){
 ...
 // for example
 return new Chart( canvas, window.params['variable'] );
 ...
}

You will get more information about this here : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer 您将在这里获得有关此的更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在网站特定页面上出现错误:浏览到index1.php文件时内部服务器错误? - Why i'm getting error on the web site specific page: Internal Server Error when browsing to index1.php file ? 使用getJSON函数抓取网页HTML尝试将调用的内容保存到变量时出现错误 - Using a getJSON function to scrape webpage HTML I'm getting an error when trying to save the contents of the call to a variable 为什么我在尝试使用 axios 发送发布请求时遇到网络错误 - Why i'm getting a network error, when trying to send a post request using axios 为什么我收到querySelectorAll()错误 - why i'm getting a querySelectorAll() error 为什么我在将 function 调用分配给变量时得到未定义,即使它是同步调用? - Why I'm getting undefined while assigning a function call to a variable even when it is a synchronous call? 为什么当我尝试运行服务器 gRPC 时出现此错误? - why i'm i getting this error when i try to run my server gRPC? 操作数组时出现错误 - I'm getting error when manipulating array 我在Ionic中得到一个未定义的变量,我不确定为什么吗? - I'mg getting an undefined variable in Ionic and I'm not sure why? 为什么我在使用 async/await 时会收到多个响应? - Why am I getting multiple responses when I'm using async/await? 为什么在将数据设置为上下文时出现最大更新深度超出错误 (React) - Why I'm getting maximum update depth exceeded error when setting data to context (React)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM