在js语言中,我们可以使用循环,比如for语句,但是在循环体之外,我们依然可以访问循环体中变量
function getValue(){
for(var i = 0 ; i<10 ; i++){
}
console.log(i);
return i ;
}

我们跳出for循环的时候,依然可以访问到i。因为声明提前的原因;在for循环启动之前,变量i其实已经创建好了。�如果我们不想在for循环体之外访问到i我们可以这样写。
function getValue(){
for(let i = 0 ; i<10 ; i++){
console.log('for循环'+i);
}
console.log(i);
return i ;
}

通过let声明变量i我们就可以控制i只能在for循环这个块作用域中访问,出了这个作用域变量i自动释放。
函数在循环体中控制
还是因为声明提前原因,让一些简单的功能执行起来十分的麻烦。
比方说,我们先声明一个数组,然后用for循环10次,将每一次的结果保存到数组中,然后我们遍历数组,将保存的数字打印出来。
var IntArray = [];
for(var i = 0; i<10; i++){
IntArray.push(function(){
console.log(i);
});
}
IntArray.forEach(function(IntArray){
IntArray();
})
你觉得程序会乖乖的打印出0~9么?

程序的确调用了10次 console.log, 但是,变量引用都是同一个i,所以,当我们调用i的时候,自然会访问到i最后一次保存的变量值,就是10。
我们要解决这个问题,可以使用return让i保存出一个副本,这样我们就可以保存不同的结果
var IntArray = [];
for(var i = 0; i<10; i++){
IntArray.push((function(j){
return function(){
console.log(j);
}
}(i)));
}
IntArray.forEach(function(IntArray){
IntArray();
})

我们将每一i单独提出来保存,这样就可得到10个不同的i
在ES6中我们其实可以这样写
var IntArray = [];
for(let i = 0; i<10; i++){
IntArray.push(function(){
console.log(i);
});
}
IntArray.forEach(function(IntArray){
IntArray();
})

因为,系统在每次迭代循环都会创造一个新的变量i,并将其值进行初始化操作,这样循环内部的函数,都可以获得一个属于他们自己的i的副本,我们就没有必要通过匿名函数进行保存副本的操作,也能达到预期效果。
键值对也可以这样操作
var ObjectArray = [],
objectName = {
name1:'莫小白',
name2:'于小沫'
};
for(let key in objectName){
ObjectArray.push(function(){
console.log(objectName[key]);
});
}
ObjectArray.forEach(function(ObjectArray){
ObjectArray();
});

最特殊的还是const,因为const是常量,所以在使用for循环的时候一定要小心。尤其不能使用在for循环中。
for(const i = 0; i < 10; i++){
console.log(i);
}

第一次运行成功!运行第二次的时候因为i是常量不能被更改,系统在执行i++的时候就会报错。
在 for-in中是可以使用const的,因为这时候循环不会更改key的值,就像之前的for-in的循环一样。这时候const创建的key不会更改值,只会创建新的绑定。
网友评论