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 相关文章推荐
js如何获取file控件的完整路径具体实现代码
May 15 Javascript
JQUERY 获取IFrame中对象及获取其父窗口中对象示例
Aug 19 Javascript
如何让浏览器支持jquery ajax load 前进、后退功能
Jun 12 Javascript
JS实现基于拖拽改变物体大小的方法
Jan 23 Javascript
在vue项目中,将juery设置为全局变量的方法
Sep 25 Javascript
基于AngularJs select绑定数字类型的问题
Oct 08 Javascript
Vue实现简单分页器
Dec 29 Javascript
node.js 基于cheerio的爬虫工具的实现(需要登录权限的爬虫工具)
Apr 10 Javascript
微信小程序 轮播图实现原理及优化详解
Sep 29 Javascript
2分钟实现一个Vue实时直播系统的示例代码
Jun 05 Javascript
如何使用vue3打造一个物料库
May 08 Vue.js
前端框架ECharts dataset对数据可视化的高级管理
Dec 24 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 无限级缓存的类的扩展
2009/03/16 PHP
php递归删除目录下的文件但保留的实例分享
2014/05/10 PHP
分享3个php获取日历的函数
2015/09/25 PHP
通过PHP设置BugFree获取邮箱通知
2019/04/25 PHP
js 函数的执行环境和作用域链的深入解析
2009/11/01 Javascript
javascript客户端解决方案 缓存提供程序
2010/07/14 Javascript
关于UTF-8的客户端用AJAX方式获取GB2312的服务器端乱码问题的解决办法
2010/11/30 Javascript
Javascript类定义语法,私有成员、受保护成员、静态成员等介绍
2011/12/08 Javascript
常用一些Javascript判断函数
2012/08/14 Javascript
js实现的复制兼容chrome和IE
2014/04/03 Javascript
FF(火狐)浏览器无法执行window.close()解决方案
2014/11/13 Javascript
JavaScript 作用域链解析
2014/11/13 Javascript
jQuery使用empty()方法删除元素及其所有子元素的方法
2015/03/26 Javascript
浅析JavaScript 调试方法和技巧
2015/10/22 Javascript
巧方法 JavaScript获取超链接的绝对URL地址
2016/06/14 Javascript
jQuery实现弹出窗口弹出div层的实例代码
2017/01/09 Javascript
jQuery插件ImgAreaSelect实现头像上传预览和裁剪功能实例讲解一
2017/05/26 jQuery
vue.js简单配置axios的方法详解
2017/12/13 Javascript
值得收藏的八个常用的js正则表达式
2018/10/19 Javascript
新手快速入门微信小程序组件库 iView Weapp
2019/06/24 Javascript
node.JS的crypto加密模块使用方法详解(MD5,AES,Hmac,Diffie-Hellman加密)
2020/02/06 Javascript
[52:31]VP vs Serenity 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
Python 过滤字符串的技巧,map与itertools.imap
2008/09/06 Python
详解Python中break语句的用法
2015/05/14 Python
Flask-WTF表单的使用方法
2019/07/12 Python
会计学应届毕业生推荐信
2013/11/04 职场文书
食堂个人先进事迹
2014/01/22 职场文书
会计电算化个人求职信范文
2014/01/24 职场文书
梅花魂教学反思
2014/04/25 职场文书
班级旅游计划书
2014/05/03 职场文书
哈姆雷特读书笔记
2015/06/29 职场文书
庆七一晚会主持词
2015/06/30 职场文书
《圆的周长》教学反思
2016/02/17 职场文书
详解如何修改nginx的默认端口
2021/03/31 Servers
用Python提取PDF表格的方法
2021/04/11 Python
在js中修改html body的样式
2021/11/11 Javascript