小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
1、在数组中查找最大值和最小值
在数值类型的数组中找到最大值和最小值
let arr = [1,2,3]
Math.max(arr)
Math.min(arr)
2、循环forEach
//循环嵌套循环
carsList.forEach(item => {
for(var i=0;i<item.product_list.length;i++){
let data ={
user_id:localStorage.user_id,
shop_cart_id:item.shop_cart_id,
index:item.product_list[i].index
}
delinfo.push(data)
}
})
//forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
//注意: forEach() 对于空数组是不会执行回调函数的。
3、find(),快速查找对象数组中,某个特定的值
在对象数组中快速找到,想要的对象数组,并且提取出来
let obj;
//原来都是用循环的数组的方法来获取的
for(var i=0;i<list.length;i++){
if(list[i].checked === true){
obj = list[i].id
return
}
}
//现在可以使用find()方法
obj = list.find(item => item.checked === true)
4、includes()
这是一个查询包含的方法,可以用来做多个值的判断;比如在判断上传文件的类型是否正确的时候
let type = file.type
//原
if (type === 'png' || type === 'jpg' || type === 'jpeg' || type ==='svg') {}
//现在
if(['png','jpg','jpeg','svg'].includes(type)){}
5、map()
返回新的数组
const users=res.items.map(item => ({
url: item.html_url,
img: item.avatar_url,
name: item.login,
})
);
6、filter(),返回符合条件的数组
let goodsList = this.goodsList.filter(item=>item.checked === true)
7、some()
对象数组中,可以把存在相同条件的对象提取成新的多个数组
let newAll = []
this.projectInfo.pro_settleList_image.forEach((item,i) => {
let index = -1
let list = newAll.some((arrItem,j) => {
if (item.sort_time === arrItem.sort_time) {
index = j;
return true;
} else {}
})
if (!list) {
newAll.push({
sort_time: item.sort_time,
subList: [item]
})
} else {
newAll[index].subList.push(item);
}
this.settleList = newAll
})
} else {this.settleList=[]}