关于前端:20220531每日小记之6个ES6中的数组函数

4次阅读

共计 1840 个字符,预计需要花费 5 分钟才能阅读完成。

所有内容均来自 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
// 办法 1
const num=1
if( num===1 || num===2 || num===3 || num===4){console.log(num)  // 1
}

// 办法 2
const nums = [1,2,3,4]
const num = 1
if (nums.includes(num) ){console.log(num)  //1
} 
  1. 应用“at 办法”读取数组尾部元素
// 办法 1
const array = [1,2,3,4,5]
const lastEle = array[array.length -1]   //5
const lastEle1 = array[-1]  //undefined

// 办法 2
const array = [1,2,3,4,5]
const lastEle = array.at(-1)  //5
const lastEle1 = array.at(0)  //1
const lastEle2 = array.at(-3)  //3
  1. flat
    flat()办法创立一个新数组,其中所有子数组元素递归连贯到指定深度
const array = [1, [ 2, [ 3, [ 4, [ 5] ] ] ] ]

// 无参数默认深度为 1
const 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 )  //0
const index2 = array.findIndex((num) => num>=10 )  //2
正文完
 0