Common ways to organize arrays

1. The method of creating an array

The first is to use the Array constructor

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

The second is Array.form()

  /** 
  	Array.form(arg1,arg2,arg3)
  	第一个参数 类数组对象,即任何可迭代的结构,或者是有一个length属性和可索引元素的结构
  	第二个参数 可选的映射函数参数,可以直接增强新数组的值,无需在调用Array.form().map()创建一个中间函数
  	第三个参数 可选 指定映射函数中this的值 但是在箭头函数中无效
  */
  
  //字符串被拆分为单字符数组
  console.log(Array.form('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]

The third is Array.of()

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

2. Method of detecting array

  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(arr) === '[object Array]'

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

3. The method of retrieving the contents of the array

  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. Copy and fill method

  /** 
  	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. Conversion method

  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. Sorting method

  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. Method of operation

  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. Search and location methods

The first method: strict equality search

  /**
	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

The second type of method searches by the assertion function
/**
This function is called for each index. The return value of the assertion function determines whether the corresponding indexed element is considered a match.
The assertion function receives 3 parameters: element, index, and the array itself. The element is the
currently searched element in the array , the index is the index of the current element, and the array is the array being searched. The assertion function returns a true value, indicating whether it matches.
*/

  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. Iterative method (traversal method)

  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. Merge method

  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. Array flattening

  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. Other methods

  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']
  

##to sum up

  改变数组自身的方法
  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

Guess you like

Origin blog.csdn.net/qq_42736311/article/details/115274807