Advertisement

Js扩展运算符知识点

阅读量:

1. 什么是扩展运算符?

三个点:

2. 用法

简单理解

用于逗号分隔的写法a, b, c, d, …和数组[a, b, c, d, …]互转

(1) 解构赋值时合并解构的值

复制代码
    const obj = {
    name: 'LuoKing',
    age: 21,
    girlFriend: 'WangBingBing',
    workingFriend: 'YueYingGeGe',
    lifeFriend: 'YiYangQianXi'
    }
    
    const arr = [1, 2, 3, 4, 5]
    
    const { name, age, ...friends } = obj
    
    console.log(name) // LuoKing
    console.log(age) // 21
    console.log(friends)
    /* 
    {
      girlFriend: 'WangBingBing',
      workingFriend: 'YueYingGeGe',
      lifeFriend: 'YiYangQianXi'
    }
    */

(2)用作函数参数,接收不定个数的参数

形参前用了扩展运算符,此形参就变成了一个数组,存放剩余传进来的参数

复制代码
    function fn(a, b, ...c) {
    console.log(a)
    console.log(b)
    console.log(c)
    }
    
    fn(1, 2, 3, 4, 5, 6, 7)
    /* 
    output:
    1
    2
    [ 3, 4, 5, 6, 7 ]
    */
    
    fn(44, 55)
    /* 
    output:
    44
    55
    []
    */

接收不定参数时,只能放到参数列表的最后,否则报错

复制代码
    function fn1(...a, b) {
    console.log(a);
    console.log(b);
    }
    
    fn1(1, 2, 3, 4);
    /*
    function fn1(...a, b) {
                 ^
    SyntaxError: Rest parameter must be last formal parameter
    */

(3)合并数组

复制代码
    let arr1 = [1, 2, 3];
    let arr2 = [4, 5, 6];
    let arr3 = [...arr1, ...arr2];
    console.log(arr3);
    // [ 1, 2, 3, 4, 5, 6 ]

(4) 字符串转字符

复制代码
    const str = 'hello';
    const arr = [...str];
    console.log(...str); // h e l l o
    // console.log(...str);相当于console.log('h', 'e', 'l', 'l', 'o');
    console.log(arr); // [ 'h', 'e', 'l', 'l', 'o' ]

全部评论 (0)

还没有任何评论哟~