Js 数组常用操作(改变数组or不改变数组)

117 阅读2分钟

改变数组的操作

  • push() :向数组的末尾添加新元素,有返回值,返回数组的长度
const arr = ["a", "b", "c", 1, 2, 4, { name: "jack", sex: "男" }];
arr.push("hello push")
console.log(arr);  // Out: [ 'a', 'b', 'c', 1, 2, 4, { name: 'jack', sex: '男' }, 'hello push' ]
  • pop():删除数组的最后一项,有返回值,返回删除的元素
const arr = ["a", "b", "c", 1, 2, 4, { name: "jack", sex: "男" }];
arr.push("hello push")
console.log(arr);  // Out: [ 'a', 'b', 'c', 1, 2, 4, { name: 'jack', sex: '男' }, 'hello push' ]
  • shift():删除数组的第一项,有返回值:返回删除的元素
const arr = ["a", "b", "c", 1, 2, 4, { name: "jack", sex: "男" }];
const shiftValue = arr.shift()
console.log(shiftValue,arr);  //Out: a [ 'b', 'c', 1, 2, 4, { name: 'jack', sex: '男' } ]
  • unshift():向数组首位添加新元素,有返回值:返回数组长度
const arr = ["a", "b", "c", 1, 2, 4, { name: "jack", sex: "男" }];
const unShiftValue = arr.unshift("5")
console.log(unShiftValue, arr);  //Out: 8 [ '5', 'a', 'b', 'c', 1, 2, 4, { name: 'jack', sex: '男' } ]
  • splice():对数组进行增删改,接受两个参数,索引(开始元素),长度(长度默认为1),有返回值, 返回切割的数组
const arr = ["a", "b", "c", 1, 2, 4, { name: "jack", sex: "男" }];
// splice(start: number, deleteCount?: number): T[]; 
const spliceValue = arr.splice(3, 1)  // 重索引下标为3的元素开始删除一个元素
console.log(spliceValue, arr); // Out: [ 1 ] [ 'a', 'b', 'c', 2, 4, { name: 'jack', sex: '男' } ]
  • sort():对数组的元素进行排序,有返回值,返回排序后的数组(默认小到大)
const arr = [2, 1, 3, 6, 5, 4, 0]
const sortValue = arr.sort()
console.log(sortValue, arr);  //Out: [0,1,2,3,4,5,6] [0,1,2,3,4,5,6]
//大到小排序 sort(fn)   sort(compareFn?: (a: T, b: T) => number): this;
console.log(arr.sort((a, b) => b - a)); //Out: [6,5,4,3,2,1]
  • reverse():反转数组,有返回值,返回排序后的数组,只是改变了元素组的内元素的位置
const arr = [2, 1, 3, 6, 5, 4, 0]
const reverseValue = arr.reverse()
console.log(reverseValue, arr);  //Out: [0, 4, 5, 6,3, 1, 2]

不改变数组的操作

  • join():用指定的分隔符将数组每一项拼接为字符串
  • slice():按照条件查找出其中的部分元素
  • indexOf():检测当前值在数组中第一次出现的位置索引
  • lastIndexOf():检测当前值在数组中最后一次出现的位置索引
  • every():判断数组中每一项都是否满足条件
  • fill(): 使用特定值填充数组中的一个或多个元素
  • concat():用于连接两个或多个数组
  • some():判断数组中是否存在满足条件的项
  • includes():判断一个数组是否包含一个指定的值
  • forEach():循环遍历数组每一项
  • map():循环遍历数组每一项
  • filter():“过滤”功能
  • copyWithin():用于从数组的指定位置拷贝元素到数组的另一个指定位置中
  • find():返回匹配的值
  • findIndex():返回匹配位置的索引
  • toLocaleString()、toString():将数组转换为字符串
  • flat()、flatMap():扁平化数组
  • entries() 、keys() 、values():遍历数组