zoukankan      html  css  js  c++  java
  • ES6 Array扩展 学习笔记

    1、Array.from() || Array.prototype.slice()

      Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。

      // NodeList对象

      let ps = document.querySelectorAll('p');

      Array.from(ps).filter(p => {

        return p.textContent.length > 100;

      });
      Array.from还可以接受第二个参数,用来对每个元素进行处理,将处理后的值放入返回的数组。

      Array.from([1, 2, 3], (x) => x * x)

      // [1, 4, 9]

    2、Array.of()

      Array.of方法用于将一组值,转换为数组。

      这个方法的主要目的,是弥补数组构造函数Array()的不足。因为参数个数的不同,会导致Array()的行为有差异。

      Array() // []

      Array(3) // [, , ,]

      Array(3, 11, 8) // [3, 11, 8]

      Array.of总是返回参数值组成的数组。如果没有参数,就返回一个空数组。

    3、find()

      find方法,用于找出第一个符合条件的数组成员。

      [1, 4, -5, 10].find((n) => n < 0) // -5

      find方法的回调函数可以接受三个参数,依次为当前的值、当前的位置和原数组。 

      [1, 5, 10, 15].findIndex(function(value, index, arr) {

      return value > 9;

      }) // 2

    4、fill()

      fill方法使用给定值,填充一个数组。

      New Array(2).fill(1) //[1,1]

      fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。

      ['a', 'b', 'c'].fill(7, 1, 2// ['a', 7, 'c']

     5、include()

      判断数组是否包含某给定的值,返回布尔值

      两个参数,参数1给定值,参数2 index 从arr[index]开始

      [1, 2, 3].includes(2) // true

      [123].includes(2,1// true

      [123].includes(2,3// false

      数组去重

       let [arr,newArr] = [[3,5,6,5,4,6,9],[]]

      arr.forEach(re=>{

        if(!newArr.includes(re)){

         newArr.push(re)

        }

      })

     6、数组去重

       拓展运算符(...)内部使用for...of循环,

         Set数据结构,它类似于数组,其成员的值都是唯一的.

              let arr = [3,5,6,5,4,6,9]
              console.log(...new Set(arr))                 //   [3,5,6,4,9]

  • 相关阅读:
    173. Binary Search Tree Iterator
    199. Binary Tree Right Side View
    230. Kth Smallest Element in a BST
    236. Lowest Common Ancestor of a Binary Tree
    337. House Robber III
    449. Serialize and Deserialize BST
    508. Most Frequent Subtree Sum
    513. Find Bottom Left Tree Value
    129. Sum Root to Leaf Numbers
    652. Find Duplicate Subtrees
  • 原文地址:https://www.cnblogs.com/-tao/p/8478060.html
Copyright © 2011-2022 走看看