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让setInteval里的函数参数中的this指向特定的对象
Jan 31 Javascript
使用按钮控制以何种方式打开新窗口的属性介绍
Dec 17 Javascript
js获取事件源及触发该事件的对象
Oct 24 Javascript
For循环中分号隔开的3部分的执行顺序探讨
May 27 Javascript
搭建pomelo 开发环境
Jun 24 Javascript
Javascript函数式编程语言
Oct 11 Javascript
JavaScript原生对象常用方法总结(推荐)
May 13 Javascript
Swiper实现轮播图效果
Jul 03 Javascript
vue-cli开发时,关于ajax跨域的解决方法(推荐)
Feb 03 Javascript
深入浅析vue中cross-env的使用
Sep 12 Javascript
vue实现侧边栏导航效果
Oct 21 Javascript
基于原生js实现九宫格算法代码实例
Jul 03 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
修改Zend引擎实现PHP源码加密的原理及实践
2008/04/14 PHP
PHP高自定义性安全验证码代码
2011/11/27 PHP
php 魔术方法详解
2014/11/11 PHP
PHP的AES加密算法完整实例
2016/07/20 PHP
php使用 readfile() 函数设置文件大小大小的方法
2017/08/11 PHP
php引用和拷贝的区别知识点总结
2019/09/23 PHP
laravel框架模型中非静态方法也能静态调用的原理分析
2019/11/23 PHP
js中巧用cssText属性批量操作样式
2011/03/13 Javascript
通过js简单实现将一个文本内容转译成加密文本
2013/10/22 Javascript
js获取select默认选中的Option并不是当前选中值
2014/05/07 Javascript
初识SmartJS - AOP三剑客
2014/06/08 Javascript
Juery解决tablesorter中文排序和字符范围的方法
2015/05/06 Javascript
jQuery弹簧插件编写基础之“又见弹窗”
2015/12/11 Javascript
Node.js开发者必须了解的4个JS要点
2016/02/21 Javascript
arcgis for js 修改infowindow样式的方法
2016/11/02 Javascript
jQuery实现点击关注和取消功能
2017/07/03 jQuery
jQuery扇形定时器插件pietimer使用方法详解
2017/07/18 jQuery
jQuery实现可兼容IE6的淡入淡出效果告警提示功能示例
2017/09/20 jQuery
基于vue-resource jsonp跨域问题的解决方法
2018/02/03 Javascript
iview通过Dropdown(下拉菜单)实现的右键菜单
2018/10/26 Javascript
vue组件库的在线主题编辑器的实现思路
2020/04/03 Javascript
Vue仿百度搜索功能
2020/12/28 Vue.js
python发送邮件接收邮件示例分享
2014/01/21 Python
Python列表(list)、字典(dict)、字符串(string)基本操作小结
2014/11/28 Python
Python中将字典转换为列表的方法
2016/09/21 Python
Python检查和同步本地时间(北京时间)的实现方法
2018/12/03 Python
python保留小数位的三种实现方法
2020/01/07 Python
Python如何实现小程序 无限求和平均
2020/02/18 Python
浅谈在django中使用filter()(即对QuerySet操作)时踩的坑
2020/03/31 Python
python中get和post有什么区别
2020/06/19 Python
CSS3 Media Queries详细介绍和使用实例
2014/05/08 HTML / CSS
干部四风问题整改措施思想汇报
2014/10/13 职场文书
2015年安置帮教工作总结
2015/05/22 职场文书
在vue中import()语法不能传入变量的问题及解决
2022/04/01 Vue.js
【海涛解说】史上最给力比赛,挑战DOTA极限
2022/04/01 DOTA
MySQL 语句执行顺序举例解析
2022/06/05 MySQL