warjiang

# 从一道题说起

``````<html>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
</body>
</html>``````

``````var nodes = document.getElementsByTagName('div');
for(var i = 0,len = nodes.length; i < len; i++){
nodes[i].onclick = function(){
console.log(i);
}
}
``````

# 分析

``````int arr[] = {1,2,3,4,5};
vector<int> v = vector<int>(arr,arr+sizeof(arr)/sizeof(int));
for(int i = 0; i < v.size(); i++){
std::cout << i << std::endl;
}``````

``````int arr[] = {1,2,3,4,5};
vector<int> v = vector<int>(arr,arr+sizeof(arr)/sizeof(int));
for(int i = 0; i < v.size(); i++){
std::cout << i << std::endl;
}
std::cout << i;``````

``````for(var i = 0;i< 5;i++){
console.log(i);
}
console.log(i);``````

``````var i;
for(i=0;i<5;i++){
console.log(i);
}
console.log(i);``````

``````var nodes = document.getElementsByTagName('div');
var i;
for(i = 0,len = nodes.length; i < len; i++){
nodes[i].onclick = function(){
console.log(i);
}
}``````

# 解决

``````var nodes = document.getElementsByTagName('div');
for(var i = 0,len = nodes.length; i < len; i++){
(function(i){
nodes[i].onclick = function(){
console.log(i);
}
})(i)

}``````

``````var nodes = document.getElementsByTagName('div');
for(var i = 0,len = nodes.length; i < len; i++){
nodes[i].onclick = (function(i){
return function(){
console.log(i);
}
})(i)
}``````

``````<!DOCTYPE html>
<html>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
let nodes = document.getElementsByTagName('div');
console.log('exec');
for(let i = 0,len = nodes.length; i < len; i++){
nodes[i].onclick = function(){
console.log(i);
}
}
</script>>
</body>
</html>``````

`<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>`引用了一个inbrower级别的es6转码器。具体可以参考babel-standalone项目.改进后的代码与原来的代码的区别在于，将`var i = 0`换成了`let i = 0`.

``````var nodes = document.getElementsByTagName('div');

var _loop = function _loop(i, len) {
nodes[i].onclick = function () {
console.log(i);
};
};

for (var i = 0, len = nodes.length; i < len; i++) {
_loop(i, len);
}``````

556 声望
14 粉丝
0 条评论