[Javascript] Advanced Function Scope
2016-04-25 16:23
731 查看
Something like 'for' or 'while', 'if', they don't create a new scope:
Everyting written in for loop can be accessed outside the for loop.
So, the problem:
Solve the problem:
var ary = [1,2,3]; for(var i = 0; i < ary.length; i++){ var greeting = "Hello"; var times = i; } console.log(i); // 3 console.log(times); // 2 console.log(greeting); // Hello
Everyting written in for loop can be accessed outside the for loop.
So, the problem:
var ary = [1,2,3]; for(var i = 0; i < ary.length; i++){ setTimeout( function(i){ console.log(ary[i]); //undefined, becaues i = 3 always }, 0) }
Solve the problem:
var ary = [1,2,3]; for(var i = 0; i < ary.length; i++){ // Function do create scope (function(){ // Remember i in j var j = i; setTimeout( function(){ // So now each j is different console.log(ary[j]); }, 0) })(); }
相关文章推荐
- js函数 获取所有用户输入数据
- iOS js oc相互调用(JavaScriptCore)(二)
- iOS js oc相互调用(JavaScriptCore) (一)
- json型数据,logstash邮件报警配置案例
- JSR 303 - Bean Validation
- JS_基础回看_tag
- 谷歌Chrome浏览器开发者工具教程—JS调试篇
- sublime JS Format js格式化工具
- cojs 自己出的题目 解题报告
- js读取COOKIE,与无法删除COOKIE
- 加断点的两个小技巧
- JS中的id和name之间的区别和使用分析
- d3.js——绘制饼状图
- 关于JS中的显示和隐藏
- 身份证 护照等js校验
- js去除数组中重复的数字
- 按钮宽度和高度固定,字体大小根据字数自适应用的javascript实现
- JSP简单介绍
- JavaScript弹出新窗口的方法
- 翻译:谷歌HTML、CSS和JavaScript风格规范