(2022-05-31)每日小记之6个ES6中的数组函数

发布时间:2024-01-02 10:00

所有内容均来自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

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号