segmentfault.com/q/:遍历修改data的值
zhuanlancom/p/:foreach遍历
foreach
//forEach是ES5中操作数组的一种方法,主要功能是遍历数组;forEach有三个参数;[].forEach(function(value,index,arrSelf){//value代表数组中的每一项;index代表数组中每一项的索引;arrSelf 代表数组本身;})var arr = [2,5,4,9];var sum = 0;arr.forEach(function(value,index,arrSelf){arrSelf[index] = value;sum+=value;});console.log(sum);
data: {personData:[100,200,300,400,500,600]},onLoad: function(options) {this.Limit()},limit(){var _this=this;this.data.personData.forEach(item=>{if (item>400) {对大于400的项进行处理}})}
上面的forEach中要对大于400的项进行修改,微信小程序里需要调用this.setData(),但是拿到的是全局的内容,如何像js中一样使用this修改呢?
可以先用一个变量保存处理后的值,全部重新处理完再重新赋值setData。
limit(){var _this=this;var temp = []this.data.personData.forEach(item=>{if (item>400) {temp.push(item) //对大于400的项进行处理,处理后再setData}})this.setData({personData:temp})}
this.setData({["personData.0"]: "设置角标为0的内容"})
