后台返回一个数组,但是缺少一个图片元素,需要循环添加三个图片,实现代码

这是data数据
list: [{
icon: require("…/…/assets/images/洗车@2x.png")
},
{
icon: require("…/…/assets/images/维修@2x.png")
},
{
icon: require("…/…/assets/images/保养@2x.png")
}
],
这是ajax返回的结果。
this.giftList = resp.result;
console.log(this.giftList);
返回如下:返回的原来是没有icon的,是处理之后的在这里插入图片描述
var arr2 = []
for (let index = 0; index < this.giftList.length; index++) {
let item = this.giftList[index]
if ((index + 1) % 3 === 0) {
this.giftList[index - 2].icon = this.list[0].icon;
this.giftList[index -1].icon = this.list[1].icon;
item.icon = this.list[2].icon;
arr2.push([this.giftList[index - 2], this.giftList[index -1], item]);
}else if(index === this.giftList.length -1 && this.giftList.length % 3 !== 0){
item.icon = this.list[1].icon;
arr2.push([item])
break
} else if(index === this.giftList.length -2 && this.giftList.length % 3 !== 0) {
item.icon = this.list[0].icon;
this.giftList[index+1].icon = this.list[1].icon;
arr2.push([item, this.giftList[index+1]])
break
}
}
console.log(arr2);
这就实现了循环添加元素的效果在这里插入图片描述
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38367710/article/details/85014204