zoukankan      html  css  js  c++  java
  • javascript小记

    一、ES10中Object.entries和Object.fromEntries的用法使用

    1.1 Object.entries({a:1,b:2}) 

    打印出来:二维数组 [["a",1],["b",1]],如下图

     1.2 Object.fromEntries([['a',1],['b',2]])

    打印出来:对象 {a: 1, b: 2},如下图

    二、ES6-数组的flat(),flatMap(),多维数组变一维数组扩展

    flat() 

    1.负责将多维数组--->一维数组。该方法返回一个新的数组,对原数据没有影响。

       [1,2,[2,3],[2,2]].flat() //[1, 2, 2, 3, 2, 2]

    2.flat()默认只会“拉平”一层,默认为1,如果想要“拉平”多层的嵌套数组,可以将flat()方法的参数写成一个整数,表示想要拉平的层数。

       [1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]]

       [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5]

    3.如果不管有多少层嵌套,都要转成一维数组,可以用Infinity关键字作为参数。 如果原数组有空位,flat()方法会跳过空位。

       [1, [2, [3,4]]].flat(Infinity) // [1, 2, 3, 4]

       [1, 2, , 4, 5].flat() // [1, 2, 4, 5]

    flatMap()

    flatMap()方法对原数组的每个成员执行一个函数,相当于执行Array.prototype.map(),然后对返回值组成的数组执行flat()方法。该方法返回一个新数组,不改变原数组。 flatMap()只能展开一层数组

     [2, 3, 4].flatMap((x) => [x, x * 2])

    // 相当于 [[2, 4], [3, 6], [4, 8]].flat()

    // [2, 4, 3, 6, 4, 8]

    三、JS 新特性:空值合并运算符的使用

    空值合并操作符??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

    逻辑或操作符(||不同,逻辑或操作符会在左侧操作数为假值时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,'' 或 0)时。

    const foo = null ?? 'default string';
    console.log(foo);
    // expected output: "default string"

    const baz = 0 ?? 42;
    console.log(baz);
    // expected output: 0

    console.log(0 || 42);

    //expected output:42

  • 相关阅读:
    Longest Common Prefix
    Roman to Integer
    Intger to Roman
    Container With Most Water
    Regular Expression Matching
    atoi
    Rotate List
    54. Search a 2D Matrix && Climbing Stairs (Easy)
    53. Minimum Window Substring
    52. Sort Colors && Combinations
  • 原文地址:https://www.cnblogs.com/liliy-w/p/14023848.html
Copyright © 2011-2022 走看看