var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …Run Code Online (Sandbox Code Playgroud)我正在开发一个应用程序,不必担心Internet Explorer,并且正在研究A +级浏览器中不存在于Internet Explorer1中的一些功能.
我想要使用的其中一个功能是JavaScript的let关键字
我似乎无法让他们的任何"让"示例在Firefox 3.6中工作(用户代理字符串:Mozilla/5.0(Windows; U; Windows NT 5.1; en-US; rv:1.9.2)Gecko/20100115 Firefox/3.6(.NET CLR 3.5.30729)).我SyntaxError: missing ; before statement在执行时得到了let foo = "bar".
那么,哪些浏览器支持let关键字?(或者我做错了什么?)
在Apple的一个头文件中libdispatch,queue.h出现以下警告:
// The declaration of a block allocates storage on the stack.
// Therefore, this is an invalid construct:
dispatch_block_t block;
if (x) {
block = ^{ printf("true\n"); };
} else {
block = ^{ printf("false\n"); };
}
block(); // unsafe!!!
// What is happening behind the scenes:
if (x) {
struct Block __tmp_1 = ...; // setup details
block = &__tmp_1;
} else {
struct Block __tmp_2 = ...; // setup details
block = &__tmp_2; …Run Code Online (Sandbox Code Playgroud) 可以使用哪些工具在类似于UML序列图的内容中传达JavaScript变量作用域和闭包等概念?例如,如何编码如下:( 臭名昭着的循环问题)
var arr = [];
for(var i=0; i<10; i++) {
arr.push(function() { alert(i); });
}
for(var j=arr.length;j--;) {
arr[j]();
}
Run Code Online (Sandbox Code Playgroud)
...在类似于这个的图表中清楚地解释:

似乎无法弄清楚这里发生了什么.
<div id="navigation">
<ul id="navList">
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX.html">Discover</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/documentation.html">Documentation</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/download.html">Download</a></li>
<li class="navItem"><a href="http://www.jacobsmits.com/placeholderRX/donate.html">Donate</a></li>
</ul>
<script type="text/javascript">
$('.navItem').each(function() {
$link = $(this).children('a');
$link.hover(
function() {
$link.css('width', '224px');
},
function() {
$link.css('width', '192px');
}
)
});
</script>
</div>
Run Code Online (Sandbox Code Playgroud)
它应该为每个链接执行它,而不是只更改最后一个链接,无论哪个链接正在悬停.
我有这个代码:
for (var i = 0; i < result.length; i++) {
// call a function that open a new "thread"
myObject.geocode({ param1: "param" }, function(results, status) {
alert(result.title[i]);
});
}
Run Code Online (Sandbox Code Playgroud)
该.geocode函数(不是我的,所以我无法编辑)打开一个新的执行"线程".
当我尝试在每一步上打印标题时,我总是得到最后一个可能值i.
如何i为每次迭代保留对正确值的引用?