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 相关文章推荐
jquery表单对象属性过滤选择器实例分析
May 18 Javascript
javascript最基本的函数汇总
Jun 25 Javascript
JSONP跨域请求实例详解
Jul 04 Javascript
Javascript 制作图形验证码实例详解
Dec 22 Javascript
详解RequireJS按需加载样式文件
Apr 12 Javascript
vue2.0s中eventBus实现兄弟组件通信的示例代码
Oct 25 Javascript
解决Angular2 router.navigate刷新页面的问题
Aug 31 Javascript
Vue.js实现tab切换效果
Jul 24 Javascript
Vue-Cli项目优化操作的实现
Oct 27 Javascript
解决vue打包 npm run build-test突然不动了的问题
Nov 13 Javascript
原生JavaScript实现购物车
Jan 10 Javascript
element el-table表格的二次封装实现(附表格高度自适应)
Jan 19 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
在“咖啡之国”感受咖啡文化
2021/03/03 咖啡文化
基于PHP+Ajax实现表单验证的详解
2013/06/25 PHP
解析isset与is_null的区别
2013/08/09 PHP
js最简单的拖拽效果实现代码
2010/09/24 Javascript
Jquery中&quot;$(document).ready(function(){ })&quot;函数的使用详解
2013/12/30 Javascript
js定时调用方法成功后并停止调用示例
2014/04/08 Javascript
js unicode 编码解析关于数据转换为中文的两种方法
2014/04/21 Javascript
深入理解JavaScript系列(33):设计模式之策略模式详解
2015/03/03 Javascript
jQuery实现字符串按指定长度加入特定内容的方法
2015/03/11 Javascript
input输入框鼠标焦点提示信息
2015/03/17 Javascript
Nodejs获取网络数据并生成Excel表格
2020/03/31 NodeJs
jQuery 自定义下拉框(DropDown)附源码下载
2016/07/22 Javascript
JQuery 动态生成Table表格实例代码
2016/12/02 Javascript
修改UA在PC中访问只能在微信中打开的链接方法
2017/11/27 Javascript
node.js中fs文件系统目录操作与文件信息操作
2018/02/24 Javascript
小程序点击图片实现自动播放视频
2020/05/29 Javascript
javascript获取select值的方法完整实例
2019/06/20 Javascript
vue实现将数据存入vuex中以及从vuex中取出数据
2019/11/08 Javascript
JavaScript setInterval()与setTimeout()计时器
2019/12/27 Javascript
vue中实现拖动调整左右两侧div的宽度的示例代码
2020/07/22 Javascript
浅谈在vue-cli3项目中解决动态引入图片img404的问题
2020/08/04 Javascript
Vue封装Axios请求和拦截器的步骤
2020/09/16 Javascript
python文件操作相关知识点总结整理
2016/02/22 Python
Python实现Pig Latin小游戏实例代码
2018/02/02 Python
Python3 导入上级目录中的模块实例
2019/02/16 Python
为什么是 Python -m
2020/06/19 Python
美国马匹用品和骑马配件购物网站:Horse.com
2018/01/08 全球购物
世界上最大的冷却器制造商:Igloo Coolers
2019/07/23 全球购物
EMU Australia澳大利亚官网:澳大利亚本土雪地靴品牌
2019/07/24 全球购物
开会迟到检讨书
2014/02/03 职场文书
小学教师师德师风演讲稿
2014/08/22 职场文书
工作时间证明
2015/06/15 职场文书
2017元旦、春节期间廉洁自律承诺书
2016/03/25 职场文书
python中Tkinter 窗口之输入框和文本框的实现
2021/04/12 Python
带你学习MySQL执行计划
2021/05/31 MySQL
nginx rewrite功能使用场景分析
2022/05/30 Servers