js数组-数组元素互换、置顶、前移一位,后移一位,前移n位、数组里面的数组合并

561 阅读2分钟

1. 两个元素换位置

 // 一、两个元素换位置
     function swapArr (arr, index1, index2) {
 //  arr.splice(index2, 1, arr[index1]) 执行这,将第4个位置替换成1下标的数据,既55替换成2,返回替换的元素组成的数组
 // 再将1位置赋值成替换后的元素。
            arr[index1] =  arr.splice(index2, 1, arr[index1])[0];
            return arr;
        }
        let arr1 = [1, 2, 4, 45, 55]
        console.log('移动前', arr1);
        console.log(swapArr(arr1, 1, 4));//[1, 55, 4, 45, 2]

ps: js 数组的splice用法

2. 将一个元素置顶

  // 二、置顶
        function toFirst (fieldData, index) {
            if (index != 0) {
                fieldData.unshift(fieldData.splice(index, 1)[0]);
            }
        }
        let arr1 = [1, 2, 4, 45, 55]
        console.log('移动前', arr1);
        toFirst(arr1, 4)
        console.log(arr1);

image.png

3.元素往前移动一位

// 三、up 上移动一格

        function upGo (fieldData, index) {
            if (index != 0) {
                fieldData[index] = fieldData.splice(index - 1, 1, fieldData[index])[0];
            } else {
                fieldData.push(fieldData.shift());
            }
        }
        let arr1 = [1, 2, 4, 45, 55]
        console.log('移动前', arr1);
        upGo(arr1, 3)
        console.log(arr1);

image.png

4. 元素向下移动一格

// 四、down 向下移动一格

        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]);
            }
        }
        let arr1 = [1, 2, 4, 45, 55]
        console.log('移动前', arr1);
        downGo(arr1, 3)
        console.log(arr1);

image.png

5. 将一个元素置底

function bottom (array, index) {
            if (index === array.length - 1) return false
            // 删除当前数组元素,并将被删除的值添加到数组末尾
            array.push(array.splice(index, 1)[0])
            return array
        }

        let arr1 = [1, 2, 4, 45, 55]
        console.log('移动前', arr1);
        bottom(arr1, 2)
        console.log(arr1);

image.png

6. 数组里面的数组合并

Array.flat()创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
   function mergeArr (arr) {
            return arr.flat(1)
        }
        let arr1 = [1, 2, 4, [1, '444'], [45, 55]]
        console.log('移动前', arr1);
        console.log(mergeArr(arr1));

image.png

二维数组合并

let arr=[[23,3],[4,5]]
let arr2=arr.flat(1)
console.log(arr2);//[ 23, 3, 4, 5 ]

7. n个元素往前移动x位


        function topre (arr, index1, index2, step) {
            arr.splice(index1 - step, 0, ...arr.splice(index1, step - 1))// 取出要移动的元素,将取出的元素插入到目标位置
        }
        const arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        console.log('移动前', arr1);
        // 将7何8往前移动4位,传入移动位置的下标,以及从7开始要动元素的个数,往前移动的位数
        topre(arr1, 6, 2, 4)
        console.log('移动后', arr1);

image.png