js对数组的常用操作以及如何在vue中封装公用方法
2019-04-30 本文已影响43人
辉夜真是太可爱啦
常用方法
1.两个数组元素换位置
function swapArr(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
}
2.将某个元素置顶
function toFirst(fieldData,index) {
if(index!=0){
// fieldData[index] = fieldData.splice(0, 1, fieldData[index])[0]; 这种方法是与另一个元素交换了位子,
fieldData.unshift(fieldData.splice(index , 1)[0]);
}
}
3.将指定元素向上移动一格
function upGo(fieldData,index){
if(index!=0){
fieldData[index] = fieldData.splice(index-1, 1, fieldData[index])[0];
}else{
fieldData.push(fieldData.shift());
}
}
4.将指定元素向下移动一格
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.shift();
return arr;
}
7.数组的去重复值,可以填任意个数组,既可以单个数组去重,也可以多个数组的合并去重
//数组合并去重
export function combine(){
let arr = [].concat.apply([], arguments); //没有去重复的新数组
return Array.from(new Set(arr));
}
方法的封装
一般在vue
中先封装成公用方法,在src
文件夹下新建一个utils
文件夹,在utils
文件夹下新建一个common.js
,例如封装第一个,将两个元素交换位置的方法,只需要在前面写个export
,你可以理解为将这个方法抛出
export function swapArr(arr, index1, index2) {
arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
}
在要使用的页面进行引用
import {swapArr} from "../utils/common";