React中常用数组方法的使用汇总:
1.forEach()
遍历每一个对象
let ids = [];
dataSource.forEach(x => {
ids.push(x.id);
})
2.filter()
filter过滤出满足条件的对象,并生成新的数组
2.1. 过滤数据
const dataSource= [
{id:'00011', name: '燃气具1'},
{id:'00012', name: '净水器1'},
{id:'00013', name: '大家电1'},
{id:'00014', name: '厨房小店1'},
{id:'00015', name: '生活电器1'},
{id:'00016', name: '配件1'}
];
const newData = dataSource.filter(v => v.id!=='00011)
2.2. 过滤数组中不存在的字段,并进行拼接
addressName: [
provinceName,
cityName,
detailaddr,
contPerson,
tel,
]
.filter(Boolean) //过滤掉为null的字段
.join('/'), //每个字段之间用 / 进行拼接
显示效果: 河南/洛阳/131.....
3.some()
遍历数组的每一项,若其中一项为 true,则返回true;
const qtyFlag = dataSource.some(x => {
return x.sinQty + x.sinQtyEd <= x.qty
})
if (!qtyFlag) {
message.warn('数量不正确')
}
4. map()
每一个元素调用一个回调函数后,返回一个新数组
levelList.map((x) => {
return (
<Checkbox
value={x.id}
key={x.id}
style={{ marginLeft: 0 }}
>
{x.name}
</Checkbox>
);
})
//生成多个复选框
5.every()
测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。
const isFlag = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isFlag));
// true
6.find()
找到满足条件的数据
const findItem = cancelReasonList.find(_ => _.code === cancelReason)
|| {
valDesc: undefined,
}
7.includes()
判断是否包含某值
option?.value.includes(val || option?.children.includes(val))
8.split()
用于把一个字符串分割成字符串数组。
reasonCodeList.filter(_=>_.es1?.split(',')?.includes('SO'))
常用的数组网站:
1.https://ramda.cn/docs/
2.https://www.lodashjs.com/
总结
以上数组方法是自己在开发过程中经常使用的,后续会继续补充(内容来自新手小白)。