当前位置:网站首页>JS for loop number exception

JS for loop number exception

2022-07-05 11:56:00 News777

Error code

const res = await getList({
    });
for(let i = 0;i < 5 - res.data.list.length;i++){
    
	res.data.list.push({
    
		day : new Date(),
		name : 'xxx'
	})
}

The reason for the error

demand res.data.list Arrays satisfy length === 5
reason : Although variable res use const Statement , But because it is an object , It does not affect the change of attribute value in the object , because res.data.list constantly push, So it's length It's changing , Therefore, the number of cycles keeps decreasing ,res.data.list.length The length of did not meet expectations

solve

const res = await getList({
    });
const len = res.data.list.length  //  increase 
for(let i = 0;i < 5 - len;i++){
      //  change 
	res.data.list.push({
    
		day : new Date(),
		name : 'xxx'
	})
}
原网站

版权声明
本文为[News777]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051148403735.html