JS数组的常用方法整理


Posted in Javascript onMarch 31, 2021

1.创建数组的方法

第一种是使用Array构造函数

参数:
  1.new Array(arg1,arg2....) //传入的参数会成为数组的每一项
  2.new Array(length) //length为数字的话返回长度为length的数组 否则创建一个只有一项length的数组

第二种是Array.from()

/** 
  	Array.from(arg1,arg2,arg3)
  	第一个参数 类数组对象,即任何可迭代的结构,或者是有一个length属性和可索引元素的结构
  	第二个参数 可选的映射函数参数,可以直接增强新数组的值,无需在调用Array.from().map()创建一个中间函数
  	第三个参数 可选 指定映射函数中this的值 但是在箭头函数中无效
  */
  
  //字符串被拆分为单字符数组
  console.log(Array.from('jerry')) //['j','e','r','r','y']
  
  //将集合和映射转换为一个新数组
  const m = new Map().set(1, 2).set(3, 4);
  const s = new Set().add(1).add(2).add(3).add(4);
  console.log(Array.from(m)); // [[1, 2], [3, 4]]
  console.log(Array.from(s)); // [1, 2, 3, 4]
  
 // 可以使用任何可迭代对象
  const iter = {
    *[Symbol.iterator]() {
      yield 1;
      yield 2;
      yield 3;
      yield 4;
    }
  };
  console.log(Array.from(iter)); // [1, 2, 3, 4]

  // arguments对象可以被轻松地转换为数组
  function getArgsArray() {
    return Array.from(arguments);
  }
  console.log(getArgsArray(1, 2, 3, 4)); // [1, 2, 3,4]

  //带有length属性的自定义对象转换为数组
  const arrayObject = {
    0: 1,
    1: 2,
    2: 3,
    3: 4,
    length: 4
  };
  console.log(Array.from(arrayObject)); // [1, 2, 3, 4]
  
  const a1 = [1, 2, 3, 4];
  const a3 = Array.from(a1, function(x) {return x**this.exponent}, {exponent: 2});
  console.log(a3); // [1, 4, 9, 16]

第三种是Array.of()

Array.of(arg1,arg2,arg3....) //可以将一组参数转换为数组
 console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4]

2.检测数组的方法

const arr = []

  //1.instanceof  arr instanceof Array

  //2.constructor arr.constructor === Array

  //3.Object.prototype.isPrototypeOf  Array.prototype.isPrototypeOf(arr)

  //4.getPrototypeOf  Object.getPrototypeOf(arr) === Array.prototype

  //5.Object.prototype.toString  Object.prototype.toString.call(arr) === '[object Array]'

  //6.Array.isArray()  Array.isArray(arr)

3.检索数组内容的方法

keys()    //返回数组的索引
  values()  //返回数组的元素
  entries() //返回索引/值对
  const arr = ["foo","bar","baz","qux"];
  const arrKeys = Array.from(a.keys());
  const arrValues = Array.from(a.values());
  const arrEntries = Array.from(a.entries());
  console.log(arrKeys); // [0, 1, 2, 3]
  console.log(arrValues); // ["foo","bar","baz","qux"]
  console.log(arrEntries); // [[0,"foo"], [1,"bar"],[2,"baz"][3,"qux"]]

4.复制填充方法

/** 
  	arr.fill(value,start,end)  向一个数组中插入全部或部分的值
  	第一个参数 用来插入或者是替换的值
  	第二个参数 开始填充的位置 可选
  	第三个参数 结束索引的位置 可选 如果有的话不包括end索引
  */
  const zeroes = [0, 0, 0, 0, 0];
  zeroes.fill(5);
  console.log(zeroes); // [5, 5, 5, 5, 5]
  zeroes.fill(6, 3);
  console.log(zeroes); // [0, 0, 0, 6, 6]
  zeroes.fill(0); 
  zeroes.fill(7, 1, 3);
  console.log(zeroes); // [0, 7, 7, 0, 0];
  zeroes.fill(0);
/** 
 	arr.copyWithin(target,start,end) )  会按照指定范围浅复制数组中的部分内容,然后将它们插入到指定索引开始的位置 不能改变原数组的长度
  	第一个参数 复制元素存放的位置 不能大于数组的长度  否则不会拷贝
  	第二个参数 开始复制元素的起始位置 可选
  	第三个参数 开始复制元素的结束位置 可选
  */
  let initArray = [0, 1, 2, 3, 4, 5, 6, 7, 8,9]
  initArray.copyWithin(4,3);
  console.log(initArray) //[0, 1, 2, 3, 3, 4, 5, 6, 7, 8]
  initArray.copyWithin(4, 3,6);
  console.log(initArray) //[0, 1, 2, 3, 3, 3, 4, 6, 7, 8]

5.转换方法

arr.valueOf()  //返回数组的本身
  arr.toString() //每个值的等效字符串拼接而成的一个逗号分隔的字符串。
  arr.toLocaleString() //得到一个逗号分隔的数组值的字符串,数组中的元都会调用toLocaleString()方法,
  let colors = ["red","blue","green"]; 
  console.log(colors.toString()) //red,blue,green
  console.log(colors.toLocaleString()) //red,blue,green
  console.log(colors.valueOf()) //["red","blue","green"]

6.排序方法

arr.reverse();//将数组的元素进行翻转,返回翻转后的数组
  
  let arr = [1,4,2,3,5,8]
  console.log(arr.reverse()) //[8, 5, 3, 2, 4, 1]
arr.sort(function(a,b){}) //对数组进行排序,返回排序后的数组,数组元素为数字,则正序排列;数组元素为字母,则按首字母ASCII码进行正序排列;数组元素为汉字,则按Unicode进行排序
  
  const array = [5,4,2,8,7,9]
  let arr1 = array1.sort((a,b)=> a - b)//升序排列
  console.log(arr1)//[2,4,5,7,8,9]
  let arr2 = array2.sort((a,b)=> b - a)//降序排列
  console.log(arr2)//[9,8,7,5,4,2]

7.操作方法

arr.concat(arg1,arg2....) //在现有数组全部元素基础上创建一个新数组它首先会创建一个当前数组的副本,然后再把它的参数添加到副本末尾
  
  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"]
  
  //打平数组参数的行为可以重写,方法是在参数数组上指定一个特殊的符号:Symbol.isConcatSpreadable 。这个符号能够阻止concat() 打平参数数组。相反,把这个值设置为 true 可以强制打平类数组对象:
  let colors2 = ["red","green","blue"];
  let newColors = ["black","brown"];
  newColors[Symbol.isConcatSpreadable] = false //不会打平数组
  let colors4 = colors2.concat(newColors)
  console.log(colors4) //["red", "green", "blue", ["black","brown"]]
  let moreNewColors ={
    [Symbol.isConcatSpreadable]:true,
    0: "pink",
    1: "cyan",
    length:2
  }
  let colors5 = colors2.concat(moreNewColors)
  console.log(colors5)//["red", "green", "blue", "pink", "cyan"]
/** 
  	arr.splice(start,delCount,item1,....) 删除、替换现有元素或者添加新元素,并返回包含从数组中被删除的元素组成的数组。
  	start    要删除的第一个元素位置
  	delCount 删除的数量
  	item1... 要插入的元素
  */
  
  let colors = ["red","green","blue"];
  let removed = colors.splice(0,1); // 删除第一项
  console.log(colors); // ["green","blue"]
  console.log(removed); //['red']
  removed = colors.splice(1, 0,"yellow","orange");
  onsole.log(colors); // ["green","blue","yellow","orange"]
  console.log(removed); //[] 空数组
/** 
 	arr.slice(start,end) 用于创建一个包含原有数组中一个或多个元素的新数组。 不会影响原数组
  	start 返回元素的开始索引
  	end   返回元素的结束索引 不包括结束索引
  */
  
  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"];
  console.log(colors2); //["green","blue","yellow","purple"];
  console.log(colors3); //["green","blue","yellow"];
arr.join(separator) //把数组中的所有元素转换成一个字符串,用参数拼接,默认以逗号拼接。
  
  const array = [1,2,3];
  console.log(array.join()); // 1,2,3
  console.log(array.join(' ')); // 1 2 3

8.搜索和位置方法

第一类方法 : 严格相等搜索

/**
	arr.indexOf(ele,index) 从数组前头(第一项)开始向后搜索,返回要查找的元素在数组中的位置,如果没找到则返回-1
	ele   要查找的元素
	index 起始搜索位置 可选
  */
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  alert(numbers.indexOf(4)); //3
/**
	arr.lastIndexOf(ele,index) 从数组末尾(第一项)开始向前搜索,返回要查找的元素在数组中的位置,如果没找到则返回-1
	ele   要查找的元素
	index 起始搜索位置 可选
  */
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  alert(numbers.lastIndexOf(4)); //5
/**
	arr.includes(ele,index) 从数组前头(第一项)开始向后搜索,返回布尔值,表示是否至少找到一个与指定元素匹配的项。
	ele   要查找的元素
	index 起始搜索位置 可选
  */
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  alert(numbers.includes(4)); //true

第二类方法 按断言函数搜索
/**
每个索引都会调用这个函数。断言函数的返回值决定了相应索引的元素是否被认为匹配。
断言函数接收3个参数:元素、索引和数组本身。其中元素是数组中
当前搜索的元素,索引是当前元素的索引,而数组就是正在搜索的数组。断言函数返回真值,表示是否匹配。
*/

arr.find((ele,idx,array) =>{},thisArg) //返回第一个匹配的元素,接受两个参数 第一个是一个断言函数,第二个是用于指定断言函数内部 this 的值 找到匹配项后不再搜索
  
  const people = [{name: "Matt",age: 27},{name: "jerry",age:29}];
  console.log(people.find((ele, index, array) =>ele.age < 28)); //{name: "Matt",age: 27}
arr.findIndex((ele,idx,array) =>{},thisArg) //返回第一个匹配的元素的索引,接受两个参数 第一个是一个断言函数,第二个是用于指定断言函数内部 this 的值 ,找到匹配项后不再搜索
  
  const people = [{name: "Matt",age: 27},{name: "jerry",age:29}];
  console.log(people.findIndex((ele, index, array) =>ele.age < 28)); //0

9.迭代方法(遍历方法)

arr.every((ele, index, array) =>{},thisArg) 对数组每一项都运行传入的函数,如果对每一项函数都返回 true ,则这个方法返回 true 。不改变调用它的数组。每个方法的函数接收3个参数:数组元素、元素索引和数组本身
  
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  let everyResult = numbers.every((item, index, array) =>item > 2);
  console.log(everyResult ) //false
arr.some((ele, index, array) =>{},thisArg) 对数组每一项都运行传入的函数,如果有一项函数返回 true ,则这个方法返回 true 。不改变调用它的数组。每个方法的函数接收3个参数:数组元素、元素索引和数组本身
  
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  let someResult = numbers.some((item, index, array) =>item > 2);
  console.log(someResult ) //true
arr.filter((ele, index, array) =>{},thisArg) 对数组每一项都运行传入的函数,函数返回 true 的项会组成数组之后返回。不改变调用它的数组。每个方法的函数接收3个参数:数组元素、元素索引和数组本身
  
  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]
arr.map((ele, index, array) =>{},thisArg) 对数组每一项都运行传入的函数,返回由每次函数调用的结果构成的数组。不改变调用它的数组。每个方法的函数接收3个参数:数组元素、元素索引和数组本身
  
  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]
arr.forEach((ele, index, array ) =>{},thisArg) 对数组每一项都运行传入的函数,没有返回值。本质上, forEach() 方法相当于使用 for 循环遍历数组。不改变调用它的数组。每个方法的函数接收3个参数:数组元素、元素索引和数组本身
  
  let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
  numbers.forEach((item, index, array) => {
    // 执行某些操作
  });

10.归并方法

arr.reduce(function(accumulator, currentValue, index, array),initialValue]) //迭代数组的所有项,并在此基础上构建一个最终返回值。从数组第一项开始遍历到最后一项。方法函数接收4个参数:上一个归并值、当前项、当前项的索引和数组本身。第二个参数是归并起点值 可选

 // reduce() 函数执行累加数组中所有数值的操作
 let values = [1, 2, 3, 4, 5];
 let sum = values.reduce((prev, cur, index, array) =>prev + cur);
 console.log(sum); // 15
arr.reduceRight(function(accumulator, currentValue, index, array),initialValue]) //迭代数组的所有项,并在此基础上构建一个最终返回值。从最后一项开始遍历至第一项。方法函数接收4个参数:上一个归并值、当前项、当前项的索引和数组本身。第二个参数是归并起点值 可选

 // reduceRight() 函数执行累加数组中所有数值的操作
 let values = [1, 2, 3, 4, 5];
 let sum = values.reduceRight((prev, cur, index, array) =>prev + cur);
 console.log(sum); // 15

11.数组扁平化

arr.flat(depth) //按照指定深度递归遍历数组,并将所有元素合并到一个新数组返回。depth为深度 默认为1
  
  const arr = [1, 2, [3, 4, [5, 6,[7,8]]]];
  let flat = arr.flat(Infinity)
  console.log(flat)//[1, 2, 3, 4, 5, 6, 7 , 8]
/**
  	arr.flatMap(function(currentValue,index,array),thisArg) 对原数组的每个成员执行一个函数(相当于执行Array.prototype.map()),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。
  	 第一个参数 遍历函数,该函数可以接受三个参数,分别是当前数组成员、当前数组成员的位置(从零开始)、原数组。
  	 第二个参数 绑定遍历函数里面的this
  */
  const arr = [[5], [8]]
  let str = arr.flatMap((currentValue)=>{
    return currentValue
  })
  console.log(str)// [5,8]

12.其他方法

arr.pop() //用于删除数组的最后一项,同时减少数组的 length 值,返回被删除的项
  
  let colors = ['red','yellow','blue']
  let item = colors.pop()
  console.log(item) //'blue'
  console.log(colors ) //['red','yellow']
arr.push(arg1,arg2...) //方法接收任意数量的参数,并将它们添加到数组末尾,返回数组的最新长度。
  
  let colors = ['red','yellow','blue']
  let item = colors.push('green','purple')
  console.log(item) //5
  console.log(colors ) //['red','yellow','blue','green','purple']
arr.shift() //删除数组的第一项并返回它,然后数组长度减1
  
  let colors = ['red','yellow','blue']
  let item = colors.shift()
  console.log(item) //'red'
  console.log(colors ) //['yellow','blue']
arr.unshift(arg1,arg2...) //在数组开头添加任意多个值,然后返回新的数组长度
  
  let colors = ['red','yellow','blue']
  let item = colors.unshift('green','purple')
  console.log(item) //5
  console.log(colors ) //['green','purple','red','yellow','blue']

##总结

改变数组自身的方法
  pop push  shift  unshift reverse sort splice copyWithin fill
不改变自身的方法
  concat join slice toString toLocateString indexOf lastIndexOf includes
遍历数组的方法 都不会改变原数组
  forEach every	some filter map reduce reduceRight entries find findIndex keys values
Javascript 相关文章推荐
javascript Array.sort() 跨浏览器下需要考虑的问题
Dec 07 Javascript
Dojo 学习要点
Sep 03 Javascript
jquery异步请求实例代码
Jun 21 Javascript
node.js实现逐行读取文件内容的代码
Jun 27 Javascript
node.js使用require()函数加载模块
Nov 26 Javascript
JQuery实现鼠标滚轮滑动到页面节点
Jul 28 Javascript
js+css实现select的美化效果
Mar 24 Javascript
JS中如何比较两个Json对象是否相等实例代码
Jul 13 Javascript
Javascript中call,apply,bind方法的详解与总结
Dec 12 Javascript
如何以Angular的姿势打开Font-Awesome详解
Apr 22 Javascript
怎样在vue项目下添加ESLint的方法
May 16 Javascript
JavaScript常用8种数组去重代码实例
Sep 09 Javascript
分享15个Webpack实用的插件!!!
JS继承最简单的理解方式
Mar 31 #Javascript
javaScript Array api梳理
Mar 31 #Javascript
抖音短视频(douyin)去水印工具的实现代码
Nest.js参数校验和自定义返回数据格式详解
Mar 29 #Javascript
Angular CLI发布路径的配置项浅析
Mar 29 #Javascript
vue中data改变后让视图同步更新的方法
You might like
聊天室php&amp;mysql(四)
2006/10/09 PHP
PHP中的类型提示(type hinting)功能介绍
2015/07/01 PHP
php 无限级分类 获取顶级分类ID
2016/03/13 PHP
JavaScript 私有成员分析
2009/01/13 Javascript
深入理解JavaScript系列(31):设计模式之代理模式详解
2015/03/03 Javascript
jQuery使用fadein方法实现渐出效果实例
2015/03/27 Javascript
jQuery+html5+css3实现圆角无刷新表单带输入验证功能代码
2015/08/21 Javascript
手机图片预览插件photoswipe.js使用总结
2016/08/25 Javascript
微信小程序 定义全局数据、函数复用、模版等详细介绍
2016/10/27 Javascript
微信小程序实现动态设置placeholder提示文字及按钮选中/取消状态的方法
2017/12/14 Javascript
详解javascript常用工具类的封装
2018/01/30 Javascript
微信小程序webview与h5通过postMessage实现实时通讯的实现
2019/08/20 Javascript
解决使用layui对select append元素无效或者未及时更新的问题
2019/09/18 Javascript
Element Badge标记的使用方法
2020/07/27 Javascript
python中的迭代和可迭代对象代码示例
2017/12/27 Python
pygame游戏之旅 计算游戏中躲过的障碍数量
2018/11/20 Python
在Python中关于使用os模块遍历目录的实现方法
2019/01/03 Python
python实现QQ邮箱/163邮箱的邮件发送
2019/01/22 Python
Python运行提示缺少模块问题解决方案
2020/04/02 Python
如何基于python把文字图片写入word文档
2020/07/31 Python
K近邻法(KNN)相关知识总结以及如何用python实现
2021/01/28 Python
HTML5 Canvas 实现圆形进度条并显示数字百分比效果示例
2017/08/18 HTML / CSS
中国旅游网站:同程旅游
2016/09/11 全球购物
Solid & Striped官网:美国泳装品牌
2019/06/19 全球购物
adidas爱尔兰官方网站:阿迪达斯运动鞋和运动服
2019/11/01 全球购物
购房协议书
2014/04/11 职场文书
拔河比赛口号
2014/06/10 职场文书
2014坚持党风廉政建设思想汇报
2014/09/18 职场文书
乡镇领导干部个人对照检查材料思想汇报
2014/09/23 职场文书
保证书格式
2015/01/16 职场文书
质量保证书怎么写
2015/02/27 职场文书
学习经验交流会演讲稿
2015/11/02 职场文书
社区结对共建协议书
2016/03/23 职场文书
大学生入党自我鉴定范文
2019/06/21 职场文书
七年级作文之雪景
2019/11/18 职场文书
win10电脑老是死机怎么办?win10系统老是死机的解决方法
2022/08/05 数码科技