简体   繁体   English

如何在javascript回调函数中传递全局变量?

[英]How to pass global variable in javascript callback functions?

I want to pass a global variable to a javascript .each function and keep its value while the iteration. 我想将全局变量传递给javascript .each函数,并在迭代时保留其值。

Here is the code. 这是代码。

 var year = false;
 page.posts.each(function(item, year){
   year = true;
 });

The year is still false. 年份仍然是错误的。 How can year keeps its value in the iteration? 年如何在迭代中保持其价值?

You have a name conflict between the function parameter and the global variable. 函数参数和全局变量之间存在名称冲突。 As the function parameter name is closer to the executed code, when JavaScript looks up through the variable names to find out what you meant, it finds the parameter name first, so that is what becomes set. 由于函数参数名称更接近于已执行的代码,因此当JavaScript在变量名称中查找以查找您的含义时,它将首先找到参数名称,因此已设置。

If you want to explicitly set the global variable, you'll have to access it though window , ie 如果要显式设置全局变量,则必须通过window来访问它,即

window.year = true; // explicit global

There is a conflict in your variable names. 您的变量名存在冲突。

var year = false;
 page.posts.each(function(item, yr){
   year = true;
 });

Try attaching to window document and see. 尝试附加到窗口文档并查看。

 window.year = false;
 page.posts.each(function(item, year){
   year = true;
 });

you can rename variable year to avoid conflict, or if you just want to change global variable , you should use window.year = true 您可以重命名变量year以避免冲突,或者如果您只想更改全局变量,则应使用window.year = true

page.posts.each(function(item, year){
   year = true;  
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM