数组的常用方法有哪些

164 阅读7分钟

image.png

一、操作方法

数组基本操作可以归纳为 增、删、改、查,需要留意的是哪些方法会对原数组产生影响,哪些方法不会

下面对数组常用的操作方法做一个归纳

下面前三种是对原数组产生影响的增添方法,第四种则不会对原数组产生影响

  • push()
  • unshift()
  • splice()
  • concat()

push()

push()方法接收任意数量的参数,并将它们添加到数组末尾,返回数组的最新长度

let colors = []; // 创建一个数组
let count = colors.push("red", "green"); // 推入两项
console.log(count) // 2

unshift()

unshift()在数组开头添加任意多个值,然后返回新的数组长度

let colors = new Array(); // 创建一个数组
let count = colors.unshift("red", "green"); // 从数组开头推入两项
alert(count); // 2

splice

传入三个参数,分别是开始位置、0(要删除的元素数量)、插入的元素,返回空数组

let colors = ["red", "green", "blue"];
let removed = colors.splice(1, 0, "yellow", "orange")
console.log(colors) // red,yellow,orange,green,blue
console.log(removed) // []

concat()

首先会创建一个当前数组的副本,然后再把它的参数添加到副本末尾,最后返回这个新构建的数组,不会影响原始数组


let colors = ["red", "green", "blue"];
let colors2 = colors.concat("yellow", ["black", "brown"]);
console.log(colors); // ["red", "green","blue"]
console.log(colors2); // ["red", "green", "blue", "yellow", "black", "brown"]

下面三种都会影响原数组,最后一项不影响原数组:

  • pop()
  • shift()
  • splice()
  • slice()

pop()

pop() 方法用于删除数组的最后一项,同时减少数组的length 值,返回被删除的项

let colors = ["red", "green"]
let item = colors.pop(); // 取得最后一项
console.log(item) // green
console.log(colors.length) // 1

shift()

shift()方法用于删除数组的第一项,同时减少数组的length 值,返回被删除的项

let colors = ["red", "green"]
let item = colors.shift(); // 取得第一项
console.log(item) // red
console.log(colors.length) // 1

splice()

传入两个参数,分别是开始位置,删除元素的数量,返回包含删除元素的数组

let colors = ["red", "green", "blue"];
let removed = colors.splice(0,1); // 删除第一项
console.log(colors); // green,blue
console.log(removed); // red,只有一个元素的数组

slice()

slice() 用于创建一个包含原有数组中一个或多个元素的新数组,不会影响原始数组

let colors = ["red", "green", "blue", "yellow", "purple"];
let colors2 = colors.slice(1);
let colors3 = colors.slice(1, 4);
console.log(colors)   // red,green,blue,yellow,purple
concole.log(colors2); // green,blue,yellow,purple
concole.log(colors3); // green,blue,yellow

即修改原来数组的内容,常用splice

splice()

传入三个参数,分别是开始位置,要删除元素的数量,要插入的任意多个元素,返回删除元素的数组,对原数组产生影响

let colors = ["red", "green", "blue"];
let removed = colors.splice(1, 1, "red", "purple"); // 插入两个值,删除一个元素
console.log(colors); // red,red,purple,blue
console.log(removed); // green,只有一个元素的数组
  // 删除选择添加的辅助人员
  const deletePersonButton = (personId) => {
    // 1.查找当前要删除的辅助人员在数组中的位置
    const indexToDelete = personSelectedDetail.value.findIndex(person => person.id === personId)
    // 2.删除提示弹窗
    uni.showModal({
      title: '提示',
      content: '确定要删除吗?',
      success: function(res) {
        if (res.confirm) {
          // 3.判断是否存在用户
          if (indexToDelete !== -1) {
            personSelectedDetail.value.splice(indexToDelete, 1);
            uni.showToast({
              title: "删除成功",
              icon: "none",
              duration: 2000
            });
            // 4.判断是否显示请选择的提示
            if (personSelectedDetail.value.length === 0) {
              selectPersonLabel.value = '请选择'
            }
            console.log(personSelectedDetail.value, '删除后剩下的用户数组')
          }
        }
      }
    })
  }

即查找元素,返回元素坐标或者元素值

  • indexOf()
  • includes()
  • find()

indexOf()

返回要查找的元素在数组中的位置,如果没找到则返回 -1

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.indexOf(4) // 3

lastIndexOf()

数组名.indexOf() :某个元素从左到右第一次出现的下标

数组名.lastIndexOf:某个元素从左到右最后一次出现的下标

var nums = [1,5,1,16,56,6,5,66]
var index = nums.indexOf(5)
console.log(index)//1

index = nums.lastIndexOf(5)
console.log(index)//6

completeMachine1Name.value = url1.substring(url1.lastIndexOf("/") + 1)
        completeMachine2Name.value = url2.substring(url2.lastIndexOf("/") + 1)
        completeMachine3Name.value = url3.substring(url3.lastIndexOf("/") + 1)
        completeMachine4Name.value = url4.substring(url4.lastIndexOf("/") + 1)

includes()

返回要查找的元素在数组中的位置,找到返回true,否则false

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.includes(4) // true

find()

返回第一个匹配的元素

const people = [
    {
        name: "Matt",
        age: 27
    },
    {
        name: "Nicholas",
        age: 29
    }
];
people.find((element, index, array) => element.age < 28) // // {name: "Matt", age: 27}
 <!-- 被选择的项目 -->
        <u-transition :show="transitionShow=true" mode="slide-right">
          <view class="select-show" v-show="showProject">
            <u-row justify="space-between">
              <view>
                <p>{{projectDetail.code}}</p>
                <p>{{projectDetail.name}}</p>
              </view>
              <u-tag :text="getStatusType(projectDetail.status).name"
                :bgColor="getStatusType(projectDetail.status).bgColor"
                :color="getStatusType(projectDetail.status).color"
                :borderColor="getStatusType(projectDetail.status).borderColor"></u-tag>
            </u-row>
          </view>
        </u-transition>
 // tag标签的status文字状态映射
  const getStatusType = (statusSelected) => {
    const cachedType = projectStatusType.value.find((item) => item.type === statusSelected);
    return cachedType || {};
  };
  // 项目状态
  const projectStatusType = ref(
    [{
        type: 0,
        name: '未立项',
        bgColor: '#FFF5EA',
        borderColor: '#FFF5EA',
        color: '#FF9934'
      },
      {
        type: 1,
        name: '未审核',
        bgColor: '#FFF5EA',
        borderColor: '#FFF5EA',
        color: '#FF9934'
      },
      {
        type: 2,
        name: '未通过',
        bgColor: '#FEEAEB',
        borderColor: '#FEEAEB',
        color: '#F4333C'
      }, {
        type: 3,
        name: '未开始',
        bgColor: '#FFF5EA',
        borderColor: '#FFF5EA',
        color: '#FF9934'
      }, {
        type: 4,
        name: '交付中',
        bgColor: '#E5EBF6',
        borderColor: '#E5EBF6',
        color: '#0542A8'
      }, {
        type: 5,
        name: '暂停中',
        bgColor: '#FEEAEB',
        borderColor: '#FEEAEB',
        color: '#F4333C'
      }, {
        type: 6,
        name: '已交付',
        bgColor: '#E9F7F4',
        borderColor: '#E9F7F4',
        color: '#29AB91'
      }, {
        type: 7,
        name: '已终止',
        bgColor: '#FEEAEB',
        borderColor: '#FEEAEB',
        color: '#F4333C'
      },
    ]
  )

二、排序方法

数组有两个方法可以用来对元素重新排序:

  • reverse()
  • sort()

reverse()

顾名思义,将数组元素方向反转

let values = [1, 2, 3, 4, 5];
values.reverse();
alert(values); // 5,4,3,2,1

sort()

sort()方法接受一个比较函数,用于判断哪个值应该排在前面

function compare(value1, value2) {
    if (value1 < value2) {
        return -1;
    } else if (value1 > value2) {
        return 1;
    } else {
        return 0;
    }
}
let values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values); // 0,1,5,10,15

三、转换方法

常见的转换方法有:

join()

join() 方法接收一个参数,即字符串分隔符,返回包含所有项的字符串

let colors = ["red", "green", "blue"];
alert(colors.join(",")); // red,green,blue
alert(colors.join("||")); // red||green||blue

toString()

把数组转成字符串------数组名.toString–对象类型数组不能直接转换

//toString() 将数组转化为字符串
var arrs = [0,1,0,1,0,52]
console.log(arrs.toString())//0,1,0,1,0,52
//相当于
console.log(`${arrs}`)//0,1,0,1,0,52

四、迭代方法

常用来迭代数组的方法(都不改变原数组)有如下:

  • some()
  • every()
  • forEach()
  • filter()
  • map()

some()

对数组每一项都运行传入的测试函数,如果至少有1个元素返回 true ,则这个方法返回 true

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let someResult = numbers.some((item, index, array) => item > 2);
console.log(someResult) // true
 // 新增装箱工单项目物料信息
  function newMaterialModel() {
    const isAlreadyAddMaterial = materialModels.value.some((detail) => detail.materialId ===
      newMaterialDetail.value.id)
    console.log(newMaterialDetail.value)
    if (!isAlreadyAddMaterial) {
      uni.request({
        url: systemConfig.value.serverUrl +
          '/service/packageWorkorder/newMaterialModel',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          count: newMaterialDetail.value.count,
          materialId: newMaterialDetail.value.id,
          projectId: workOrderDetail.value.projectId,
          workorderId: globalId.value,
          projectMaterialModel: newMaterialDetail.value
        },
        success: function(res) {
          console.log('新增成功')
          // 获取装箱工单项目物料列表
          getMaterialModelsById()
        },
        fail: function(err) {
          console.log(err);
        }
      });
    } else {
      uni.showToast({
        title: "该物料已扫描过",
        icon: "none",
        duration: 2000
      });
    }

  }

every()

对数组每一项都运行传入的测试函数,如果所有元素都返回 true ,则这个方法返回 true

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let everyResult = numbers.every((item, index, array) => item > 2);
console.log(everyResult) // false

forEach()

对数组每一项都运行传入的函数,没有返回值

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
numbers.forEach((item, index, array) => {
    // 执行某些操作
});

filter()

对数组每一项都运行传入的函数,函数返回 true 的项会组成数组之后返回

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let filterResult = numbers.filter((item, index, array) => item > 2);
console.log(filterResult); // 3,4,5,4,3

map()

对数组每一项都运行传入的函数,返回由每次函数调用的结果构成的数组

let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let mapResult = numbers.map((item, index, array) => item * 2);
console.log(mapResult) // 2,4,6,8,10,8,6,4,2
 // 处理辅助人员
        const userModels = workOrderDetail.value.userModels.map(user => user.name).join(',')
        if (userModels !== null) {
          assistUserName.value = userModels
        }
  // 获取打印机列表
  function getPrinterModels() {
    uni.request({
      url: systemConfig.value.serverUrl +
        '/service/printer/getModels',
      method: 'GET',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        code: '',
        name: '',
        type: 1,
      },
      success: function(res) {
        // 1.赋值
        printList.value = res.data.body
        console.log(printList.value)
        // 2.判断是否存在打印机
        if (printList.value.length === 0) {
          printColumns.value[0] = ['无']
        } else {
          // 3.筛选打印机类型(适用于打印工单的打印机)

          // 4.遍历code并且赋值给弹窗
          const printCodeList = printList.value.map(item => item.code)
          const printNameList = printList.value.map(item => item.name)
          printColumns.value[0] = printNameList
        }

      },
      fail: function(err) {
        console.log(err);
      }
    });
  }

案例

  // 处理已存储的辅材列表(新增,删除)
  function seletedAuxiliaryListHandle() {
    // 存储需要删除的辅材ID
    const auxiliaryToDelete = [];
    seletedAuxiliaryList.value.forEach(auxiliary => {
      if (!selectedItem.value.includes(auxiliary.id))
        // 将需要删除的设备的 ID 存储在 auxiliaryToDelete 中
        auxiliaryToDelete.push(auxiliary.id)
    })
    // 从 seletedAuxiliaryList 中删除 auxiliaryToDelete 中的设备
    auxiliaryToDelete.forEach(auxiliaryId => {
      const index = seletedAuxiliaryList.value.findIndex(d => d.id === auxiliaryId);
      if (index !== -1) {
        seletedAuxiliaryList.value.splice(index, 1);
      }
    })

    selectedItem.value.forEach(itemId => {
      const itemList = dataList.value.find(d => d.id === itemId);
      if (itemList && !seletedAuxiliaryList.value.some(d => d.id === itemList.id)) {
        // 如果选中的辅材存在,但不在 seletedAuxiliaryList 中,添加它
        seletedAuxiliaryList.value.push(itemList);
      }
    })
    console.log('34123123123125423')
    console.log(selectedItem.value)
    console.log(seletedAuxiliaryList.value)
  }
 // 新增图片
  const afterRead = async (event) => {
    // 当设置 mutiple 为 true 时, file 为数组格式,否则为对象格式
    let lists = [].concat(event.file);
    let fileListLen = fileList1.value.length;
    lists.map(async (item) => {
      fileList1.value.push({
        ...item,
        status: 'uploading',
        message: '上传中',
      });
    });

    for (let i = 0; i < lists.length; i++) {
      const result = await uploadFilePromise(lists[i].url);
      let item = fileList1.value[fileListLen];
      fileList1.value.splice(fileListLen, 1, {
        ...item,
        status: 'success',
        message: '',
        url: result,
      });
      fileListLen++;
    }
  };