js对数组操作移动进行封装

//1.两个数组元素换位置

export  function swapArr(arr, index1, index2) {
    
    
arr[index1] = arr.splice(index2, 1, arr[index1])[0];

return arr;

}

//2.将某个元素置顶

export  function toFirst(fieldData,index) {
    
    
if(index!=0){
    
    
// fieldData[index] = fieldData.splice(0, 1, fieldData[index])[0]; 这种方法是与另一个元素交换了位子,

fieldData.unshift(fieldData.splice(index , 1)[0]);

}

}

//3.将指定元素向上移动一格

export  function upGo(fieldData,index){
    
    
if(index!=0){
    
    
fieldData[index] = fieldData.splice(index-1, 1, fieldData[index])[0];

}else{
    
    
fieldData.push(fieldData.shift());

}

}

//4.将指定元素向下移动一格

export  function downGo(fieldData,index) {
    
    
if(index!=fieldData.length-1){
    
    
fieldData[index] = fieldData.splice(index+1, 1, fieldData[index])[0];

}else{
    
    
fieldData.unshift( fieldData.splice(index,1)[0]);

}

}

//5.数组内两个元素换位子

export function swapArr(arr, index1, index2) {
    
    
arr[index1] = arr.splice(index2, 1, arr[index1])[0];

return arr;

}

//6.将数组任意位置的元素移动到末尾

export function toEnd(arr,index) {
    
    
arr.push(arr[index]);

arr.splice(index,1);

return arr;

}

//7.数组的去重复值,可以填任意个数组,既可以单个数组去重,也可以多个数组的合并去重

//数组合并去重

export function combine(){
    
    
let arr = [].concat.apply([], arguments); //没有去重复的新数组

return Array.from(new Set(arr));

}

//8.删除指定元素,第一个参数为要删除元素的数组,第二个参数为要删除的元素值,第三个值为是否开启严格模式(变量类型严格比较) 例如removeArr([1,2,3,4,5],2,false) 返回[1,3,4,5] 例如removeArr([1,2,3,4,5],2,true) 返回[1,2,3,4,5]

export function removeArr (arr,val,strict) {
    
    
let index;

if(strict===true){
    
    
index = arr.findIndex(x=>x===value);

}else{
    
    
index = arr.findIndex(x=>x==value);

}

if (index > -1) {
    
    
arr.splice(index, 1);

}

}


export function swapArr(arr, index1, index2) {
    
    
arr[index1] = arr.splice(index2, 1, arr[index1])[0];

return arr;

}

猜你喜欢

转载自blog.csdn.net/weixin_45932157/article/details/126050413