所有内容均来自web前端开发微信公众号文章,记录作为学习笔记
2022-05-31
知识点目录
  • Array.of
  • Array.from
  • includes
  • 应用at办法读取数组的尾部元素
  • flat
  • findIndex
  1. Array.of与Array的区别

留神察看示例的区别:

const array1-1 = Array(3)  //[ , , ]const array1-2 = Array.of(3)  //[3]const array2 = Array() // []const array3 = Array(undefined) // [ undefined ]const array4 = Array(1, 2, 3) // [ 1, 2, 3 ]const array2 = Array.of() // []const array3 = Array.of(undefined) // [ undefined ]const array4 = Array.of(1, 2, 3) // [ 1, 2, 3 ]
  1. Array.from
    from办法中,能够通过Array.from办法将类数组对象、arguments对象、NodeList对象转换为真正的数组。
    1)类数组元素
const arrayLike = {0:'fatfish',1:'medium',length:2}const array1 = [].slice.call(arrayLike)   // ['fatfish', 'medium']const array2 = Array.from(arrayLike)   // ['fatfish', 'medium']

2)节点列表

const domsNodeList = document.querySelectorAll('div')const domsArray = Array.from(domsNodeList) // [ dom, dom, dom, ... ]

3)Arguments

const logInfo = function () {  console.log('arguments', arguments)  console.log('Array.from arguments', Array.from(arguments))}logInfo('fatfish', 100)logInfo('fatfish')

4)Array.from的第二个参数
能够应用Array.from办法,如 "[].map"

const array = [1,2,3]const array2 = array.map( (num) => num*2 )  //[2,4,6]const array3 = Array.from( array , (num) => num*2 )  //[2,4,6]
  1. includes
//办法1const num=1if( num===1 || num===2 || num===3 || num===4 ){console.log(num)  // 1}//办法2const nums = [1,2,3,4]const num = 1if ( nums.includes(num) ){console.log(num)  //1} 
  1. 应用“at办法”读取数组尾部元素
//办法1const array = [1,2,3,4,5]const lastEle = array[ array.length -1 ]   //5const lastEle1 = array[-1]  //undefined//办法2const array = [1,2,3,4,5]const lastEle = array.at( -1 )  //5const lastEle1 = array.at( 0 )  //1const lastEle2 = array.at( -3 )  //3
  1. flat
    flat()办法创立一个新数组,其中所有子数组元素递归连贯到指定深度
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]//无参数默认深度为1const flat1  = array.flat()  //[1,2,[3,[4,[5]]]]const flat2  = array.flat(2)  //[1,2,3,[4,[5]]]const flat3  = array.flat(Infinity)  //[1,2,3,4,5]
  1. findIndex
    findIndex()办法返回数组中满足提供的测试函数的第一个元素的索引,否则,她返回-1,示意没有元素通过测试
const array = [ -1, 0, 10, 10,  20, 100 ]const index1 = array.findIndex( (num) => num<0 )  //0const index2 = array.findIndex( (num) => num>=10 )  //2