数组中元素的操作
const arr = [1, 2, 3, 4];
this.removeByValue(4);
console.log(arr); // [1, 2, 3]
this.addByValue(6);
console.log(arr); // [1, 2, 3, 6]
复制代码
1、关于数组元素的减少
removeByValue = (val) => { // 减少指定的数组元素
for (let i = 0; i < arr.length; i += 1) {
if (arr[i] === val) {
this.arr.splice(i, 1);
return;
}
}
}
复制代码
2、数组的元素为对象时,可以根据唯一key,来进行确认减少(比第一种简便)
const newData = this.arr.filter(item => item.key !== key);
复制代码
3、关于数组元素的增加
addByValue = (val) => { // 增加元素
this.arr.push(val);
}
复制代码
4、有数组中,取出key值为K的对象元素
const target = arr.find(item => item.key === no);
复制代码
5、两个数组之间,进行相关的操作
const arr1 = [1,2,3];
const arr2 = [3,4,5];
// 并集
const union = Array.from(new Set([...arr1,...arr2])); // union = [1,2,3,4,5]
// 交集
const intersection = Array.from(new Set([...arr1].filter(x => new Set(arr2).has(x)))); // intersection = [3]
// 差集
const difference1 = Array.from(new Set([...arr1].filter(x => !new Set(arr2).has(x)))); // difference1 = [1,2]
const difference2 = Array.from(new Set([...arr2].filter(x => !new Set(arr1).has(x)))); // difference2 = [4,5]
复制代码
6、置换数组之间的位置(实战:在table中,可以置换位置)
swapItems = (arr, index1, index2) => {
const arrData = arr;
arrData[index1] = arrData.splice(index2, 1, arrData[index1])[0];
return arr;
}
复制代码
upRecord(no) {
const newData = this.state.selectedMaterialList.slice(0);
const target = newData.find(item => item.key === no);
const index = newData.indexOf(target);
if (index === 0) {
message.warn('此模板为第一条,无法上移', 1.5);
} else {
const data = this.swapItems(newData, index, index - 1);
this.setState({ selectedMaterialList: data });
}
}
复制代码
downRecord(no) {
const newData = this.state.selectedMaterialList.slice(0);
const target = newData.find(item => item.key === no);
const index = newData.indexOf(target);
if (index === newData.length - 1) {
message.warn('此模板为最后一条,无法下移', 1.5);
} else {
const data = this.swapItems(newData, index, index + 1);
this.setState({ selectedMaterialList: data });
}
}
复制代码