数组 array

需要查找的方法:

  • 第一个匹配的元素,使用 find()
  • 数组中最后一个匹配元素的索引,使用 findLastIndex()
  • 值的索引,使用 Array.prototype.indexOf()。(它类似于 findIndex(),但是会检查每个元素是否和值相等,而不是使用一个测试函数。)
  • 一个值是否包含在该数组中,使用 Array.prototype.includes()。同样地,它检查每个元素是否和值相等,而不是使用一个测试函数。
  • 是否有任意一个元素满足提供的测试函数,使用 Array.prototype.some()

1,copyWithin

  // 会改变原数组
  let arr = [1,2,3,4,5,6,7,8,9,0]//长度为原数组的长度
  // console.log(arr.copyWithin(3));
  // console.log(arr.copyWithin(3,4));
  console.log(arr.copyWithin(3,4,5))
  //3代表数组从第几个开始替换,4代表从原数组第几个开始往后排,5代表结束位置,4开始,5结束,其他不变

2,entries

 // 不会改变原数组entries
  const a = ["a", "b", "c"]
  for (const [index, element] of a.entries()){//entries() 方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。
    console.log(index, element)//一个新的 Array 迭代器对象。
  }
  const aEntries = a.entries()
  for (const element of aEntries) {
    console.log(element)//输出每个元素对应的数组,第一个元素是索引值,第二个是值
  }
  for (const element of [,"a"].entries()){
    console.log(element)//可访问空槽,输出undefined
  }
  const aLike = {//在非数组对象上调用 entries()
    length: 3,
    0: "a",
    1: 'b',
    2: 'c'
  }//entries() 方法读取 this 的 length 属性,然后访问每个整数索引。
  for (const entry of Array.prototype.entries.call(aLike)) {
    console.log(entry)
  }

3,fill

 //会改变原数组
  const array1 = [1,2,3,4]
  //console.log(array1.fill(0,2,5))//填充的值是0,从第2个开始(不包含),到第5个结束{由于数组长度只有4个,所以数组只有4个}
  // console.log(array1.fill(0,3))//填充0,从第3个开始(不包含),到末尾
  console.log(array1.fill(6))//所以数组元素填充6

4,filter

// 一个新的、由通过测试的元素组成的数组,如果没有任何数组元素通过测试,则返回空数组。
  const words = ['apple', 'per', 'banana', 'orange', 'lemon']
  const result = words.filter(words => words.length > 5)//filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。
  console.log(result)//输出字母>5 的单词

5,find(返回元素)

const arr2 = [1,3,5,7,9,,2,4,6,8,0]//find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。
  const found = arr2.find(element => element>6)
  console.log(found)//返回元素

6,findIndex(同上,返回第一个满足条件的索引)

7,findLast

  const arr3 = [5,12,23,57,3576,566]
  const found1 = arr3.findLast((element)=>element>45)//findLast() 方法返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回 undefined。
  console.log(found1)

8.findLastIndex(同上,返回最后一个满足条件的索引)

9.flat

const arr4 = [1,2,[[[[[[[[[[3,4]]]]]]]]]]]
  console.log(arr4.flat())//默认少一层[]
  console.log(arr4.flat(4))//少四层[]
  console.log(arr4.flat(Infinity))//少所以
  const arr4_1 = [1, , ,2,3]
  console.log(arr4_1.flat())//移除空项

10.flatMap

const arr5 = [1,2,[3],[4,5],6,[]]//移除空项,去除每个[],并合并成一个新的数组
  const flattened = arr5.flatMap(num => num)//输出符合条件的
  console.log(flattened)
  var arr1 = [1,2,3,4]
  var arr1_1 = arr1.map(x=> [x*2])//map()一个大数组包含每个元素数组[[1],[2]...]
  console.log(arr1_1)
  var arr1_2 = arr1.flatMap(x=>[x*2])//flatMap()返回新数组[1,2,3...]
  console.log(arr1_2)
  var arr1_3 = arr1.flatMap(x=>[[x*2]])//同map()
  console.log(arr1_3)
  let arr6 = ['Hope everything goes well', '', 'was very happy today']
  let arr6_1 = arr6.map(x=>x.split(' '))
  console.log(arr6_1)
  let arr6_2 = arr6.flatMap(x=>x.split(' '))
  console.log(arr6_2)//输出列表长度可以不同于输入列表长度,修改items数量

11.forEach()

const arr7 = ['a', 'b', 'c', 'd']
  arr7.forEach((element, index, array) => console.log(element, index, array))//forEach() 方法对数组的每个元素执行一次给定的函数
  const items = ['item1', 'item2', 'item3']
  const copyItems = []
  // for (let i = 0;i< items.length;i++){
  //   console.log(copyItems.push(items[1]))
  // }//同上,会改变原数组
  items.forEach((item)=>{
    console.log(copyItems.push(item))
  })

12,from

 //from 创建新的数组
  console.log(Array.from('foo'))//string,输出['f','o','o']
  console.log(Array.from([1,2,3],x=>x+x))//[2,4,6]
  const set = new Set(['foo', 'bar', 'baz', 'foo'])
  console.log(Array.from(set))//[ "foo", "bar", "baz" ]去重
  const map = new Map([[1,2],[2,4],[4,8]])
  console.log(Array.from(map))//不变
  const mapper = new Map([['1','a'], ['2','b']])//前面数字变成索引,后面字母变成值
  console.log(Array.from(mapper.values()))//输出值
  console.log(Array.from(mapper.keys()))//输出索引
  function f() {
    return Array.from(arguments)//arguments类数组对象
  }
  console.log(f(1,2,3))
  console.log(Array.from([1,2,3], x=>x+x))//箭头函数
  console.log(Array.from({length: 5},(v,i)=>i))
const range = (start, stop, step)=>Array.from({ length: (stop-start) /step+1},(_, i)=>start+(i*step))
  console.log(range(0,4,1))//[0,1,2,3,4]
start=0,stop=4,step=1 
length: (4-0)/1+1=5,    =>0+(1*1)       输出[0,1,2,3,4]

// range(a,b,c)a到b之间,[a+c, a+c+c, ...a+c<=b]

 数组去重合并

function combine(){
    let arr = [].concat.apply([], arguments)
    return Array.from(new Set(arr))
  }
  var m = [1,2,3,4,2,1,], n = [4,8,4,1,6,8]
  console.log(combine(m,n))

 13.includes

const arr8 = [1,2,3]
  console.log(arr8.includes(2))//用来判断一个数组是否包含一个指定的值(true,false)

14.indexOf

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']//indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。
  console.log(beasts.indexOf('bison'))//第一个bison出现的位置
  console.log(beasts.indexOf('bison', 2))//第二个bison出现的位置
  console.log(beasts.indexOf('gjtigth'))//不在数组内,输出-1
  //找出指定元素出现的所有位置
  const indices = []
  const arr9 = ['a','b','a','c','a','d']
  const element = 'a'
  let idx = arr9.indexOf(element)//初始idx为第一个a所在地
  while(idx !== -1){//循环到indexOf找不到a的索引为止
    indices.push(idx) //在末尾添加找到的索引
    idx = arr9.indexOf(element, idx+1)//重新赋值给idx,每次循环都把开始查找的位置+1
  }
  console.log(indices)

15.isArray

console.log(Array.isArray([1,2,3]))//用于确定传递的值是否是一个 Array。

16,join

所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。

const element1 = ['fire', 'air', 'water']
  console.log(element1.join())
  console.log(element1.join(''))
  console.log(element1.join('-'))
  console.log([1,,3].join())//1,3
  console.log([1,undefined,3].join())// 空槽=undefined,并产生额外的分隔符
const arrLike = {
    length:3,
    0:2,
    1:3,
    2:4
  }//在非数组对象上调用 join() 方法读取 this 的 length 属性,然后访问每个整数索引。
  console.log(Array.prototype.join.call(arrLike))
  console.log(Array.prototype.join.call(arrLike, '.'))

17.keys

返回一个包含数组中每个索引键的 Array Iterator 对象。

const arr11 = ['a', 'b', 'c']
  const iterator = arr11.keys()
  for (const key of iterator){
    console.log(key)//输出索引0,1,2
  }
  var arr11_1 = ['a', , 'c']//索引迭代器会包含那些没有对应元素的索引
  var sparseKeys = Object.keys(arr11_1)
  var denseKeys = [...arr11_1.keys()]
  console.log(sparseKeys)
  console.log(denseKeys)

18,lastIndexOf(同IndexOf,默认倒数的第一个索引)

const animals = ['dodo', 'tiger', 'penguin', 'dodo']
  console.log(animals.lastIndexOf('dodo'))//返回这个元素最后出现在数组的位置,3
  console.log(animals.lastIndexOf('tiger'))

  var indices1 = []
  var arr12 = ['a', 'b', 'a', 'c', 'a', 'd']
  var element2 = 'a'
  var idx1 = arr12.lastIndexOf(element2)
  while(idx1!=-1){
    indices1.push(idx1)
    idx1 = (idx1 > 0 ? arr12.lastIndexOf(element2, idx1-1) : -1)//如果是第一个元素,忽略了fromIndex参数则第一个元素总会被查找。
  }//idx > 0时,才进入 lastIndexOf 由后往前移一位进行倒查找;如果idx == 0则直接设置idx = -1,循环while (idx != -1)就结束了。
  console.log(indices1)

19.map

const arr13 = [2,4,8,16]
  const map1 = arr13.map(x=>x*2)//创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
  console.log(map1)//一个新数组,每个元素都是回调函数的返回值。
  const numbers = [1,4,9]
  const roots = numbers.map((num) => Math.sqrt(num))//原数组中对应数字的平方根
  console.log(numbers,'|',roots)
  const kvArray = [
    {key: 1,value: 10},
    {key: 2,value: 20},
    {key: 3,value: 30},
  ]//使用一个包含对象的数组来重新创建一个格式化后的数组
  const reformattedArray = kvArray.map(({key, value})=>({[key]:value}))
  console.log(kvArray,'|',reformattedArray)

  const elems = document.querySelectorAll('select option:checked');
  const values = Array.prototype.map.call(elems, ({ value }) => value);

  const numbers1 = [1,2,3,4]//映射包含 undefined 的数组
  const filteredNumbers1 = numbers1.map((num, index)=>{
    if(index<3){
      return num
    }
  })
  console.log(filteredNumbers1)

20.Array.of() 方法通过可变数量的参数创建一个新的 Array 实例,而不考虑参数的数量或类型

21.pop 从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度

const plants = ['joyful', 'happle', 'luck', 'cheerful', 'unhapple']
  const pop1 = plants.pop()
  console.log(pop1)
  console.log(plants)

22.reduce

数组中的每个元素按序执行一个 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。

const arr14 = [1,2,3,4]
  const initialValue = 0
  const sumWithInitial = arr14.reduce(
    (previousValue, currentValue)=>previousValue+currentValue,
    initialValue//第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
  )//0+1,0+1的值+2...l
  console.log(sumWithInitial)

23,reduceRight

方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。

var sum = [0,1,2,3,4,5].reduceRight(function(a, b){
    return a + b
  })
  console.log(sum)//5+4, (5+4)+3,......

24,reverse

const a1 = [1,2,3,4]
  a1.reverse()//倒转数组1,2,3变成3,2,1
  console.log(a1)

  const a2 = {0:1, 1:2, 2:3, length:3}
  Array.prototype.reverse.call(a2)
  console.log(a2)//输出{0:3, 1:2, 2:1, length:3}

25.shift

从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

const arr15 = [1,2,3]
  const firstElement = arr15.shift()
  console.log(arr15)
  console.log(firstElement)
  var names = ['Happy', 'delighted', 'excited', 'surprised']
  while ((i=names.shift())!==undefined) {
    console.log(i)//删除所有数组
  }

26.slice

const animals2 = ['ant', 'bison', 'car', 'dog']
  console.log(animals2.slice(1,4))//复制从1到4的所有元素, arr.slice(1)从一开始到结束,arr.slice()复制全部

27.sone

测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。 如果用一个空数组进行测试,在任何情况下它返回的都是false

const arr16 = [1,2,3,4,5]
  const even = (element) =>element%2 ===0
  console.log(arr16.some(even));//测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。

28.sort

const moths = ['March', 'Jan', 'Feb', 'Dec']
  moths.sort()
  console.log(moths)//用原地算法对数组的元素进行排序,

29,splice

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

const abc = ['a', 'b', 'c', 'd']
  abc.splice(3, 2, 'e', 'f', 'g')//从索引3开始(0,从头开始),删除2个元素(0不删除),添加3个元素(没有不添加)
  console.log(abc)//['a', 'b', 'c', 'e', 'f', 'g']

30,toLocaleString

返回一个字符串表示数组中的元素。数组中的元素将使用各自的 toLocaleString 方法转成字符串,这些字符串将使用一个特定语言环境的字符串(例如一个逗号 ",")隔开。

const array2 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
  const localeString = array2.toLocaleString('en', { timeZone: 'UTC' });
  console.log(localeString);

  var prices = ['¥7',66,888,666]
  prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
  console.log(prices)

31,toString

返回一个字符串,表示指定的数组及其元素。

const arr17 = [1,2,7,'a']
  console.log(arr17.toString())//返回"1,2,7,a"(一个字符串)

32.unshift()

将一个或多个元素添加到数组的开头,并返回该数组的新长度

const arr18 = [1, 2, 3]
  console.log(arr18.unshift(4,5))//返回新数组长度
  console.log(arr18)//新数组,4,5,在1,2,3前面

33.values()

返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值。

const arr19 = ['a','b','c']
  const iterator1 = arr19.values()
  for (const value of iterator1){
    console.log(value)
  }

猜你喜欢

转载自blog.csdn.net/m0_72698039/article/details/127791486