Javascript循环只使用最后一个值 [英] Javascript loop only use the last value
本文介绍了Javascript循环只使用最后一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让stars = [];
//循环5次
for(var i = 1; i< = 5; i ++){
//设置填充星的路径
let path = require( './star-filled.png');
if(i> this.state.cRating){
path = require('./ star-unfilled.png');
}
stars.push((< TouchableHighlight onPress = {_ => this._RateApp(i)}>< Image style = {styles.image} source = {path} /> ;< / TouchableHighlight>));
}
在
this._RateApp(i)
函数中,我得到的所有图像的值都是6。请解释。
我尝试过:
关闭 - 处理javascript中的循环,只有最后一项受到影响? - 堆栈溢出 [ ^ ]
解决方案
循环变量问题! [ ^ ]
关闭循环变量在JavaScript中同样有害因为它在C#中,修复起来比较麻烦 - 旧的新事物 [ ^ ]
闭包 - JavaScript | MDN [ ^ 一>
let stars = []; // Loop 5 times for (var i = 1; i <= 5; i++) { // set the path to filled stars let path = require('./star-filled.png'); if (i > this.state.cRating) { path = require('./star-unfilled.png'); } stars.push((<TouchableHighlight onPress={ _ => this._RateApp(i) }><Image style={styles.image} source={path} /></TouchableHighlight>)); }
In
this._RateApp(i)
function, I am getting the value of i as 6 for all the images.Please explain.
What I have tried:
closures - dealing with loops in javascript, only last item gets affected? - Stack Overflow[^]
解决方案
Loop variable gotcha![^]
Closing over the loop variable is just as harmful in JavaScript as it is in C#, and more cumbersome to fix – The Old New Thing[^]
Closures - JavaScript | MDN[^]
这篇关于Javascript循环只使用最后一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文