[js] 扩展运算符 ... spread syntax

可以不再使用Apply去调用函数

Function.prototype.apply ,传递一个参数数组,调用一个函数,并把数组中的每一项拆分成单个参数传递给函数:

  • Math.min
    // ES5 的写法  
    Math.max.apply(null, [14, 3, 77])  
    // ES6 的写法  
    Math.max(...[14, 3, 77])  
    //  等同于  
    Math.max(14, 3, 77);  
  • push
    // ES5 的写法  
    var arr1 = [0, 1, 2];  
    var arr2 = [3, 4, 5];  
    Array.prototype.push.apply(arr1, arr2);  
    
    // ES6 的写法  
    var arr1 = [0, 1, 2];  
    var arr2 = [3, 4, 5];  
    arr1.push(...arr2);

//unshift类似 
  • date
    // ES5  
    new (Date.bind.apply(Date, [null, 2015, 1, 1]))  
    // ES6  
    new Date(...[2015, 1, 1]);  

合并/复制 数组

    (浅复制)直接复制创建一个不改变原数组的数组
    // ES5
    let new = [].concat(old); 或 let new = old.concat([]);
    或
    let new = old.slice(0,old.length);
    // ES6
     let new = [...old];

    // ES5  
    [1, 2].concat(more)  
    // ES6  
    [1, 2, ...more]  
    
    var arr1 = ['a', 'b'];  
    var arr2 = ['c'];  
    var arr3 = ['d', 'e'];  
    // ES5 的合并数组  
    arr1.concat(arr2, arr3);  
    // [ 'a', 'b', 'c', 'd', 'e' ]  
    // ES6 的合并数组  
    [...arr1, ...arr2, ...arr3]  
    // [ 'a', 'b', 'c', 'd', 'e' ]  

把arguments或NodeList转为数组

[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]  


//还可让arguments在传递时就变成一个数组:

    // ES5 的写法  
    function f(x, y, z) {  
    // ...  
    }  
    var args = [0, 1, 2];  
    f.apply(null, args);  
    
    // ES6 的写法  
    function f(x, y, z) {  
    // ...  
    }  
    var args = [0, 1, 2];  
    f(...args);  

//用Array.from也能达到效果

与解构赋值结合

    // ES5  
    a = list[0], rest = list.slice(1)  
    // ES6  
    [a, ...rest] = list  
    
    下面是另外一些例子。  
    const [first, ...rest] = [1, 2, 3, 4, 5];  
    first // 1  
    rest // [2, 3, 4, 5]  
    
    const [first, ...rest] = [];  
    first // undefined  
    rest // []:  
    
    const [first, ...rest] = ["foo"];  
    first // "foo"  
    rest // []  

    
//如果将扩展运算符用于数组赋值,只能放在参数的最后一位,否则会报错。
    const [...butLast, last] = [1, 2, 3, 4, 5];  
    //  报错  
    const [first, ...middle, last] = [1, 2, 3, 4, 5];  
    //  报错  

将字符串转为数组

    let str = 'hello';
    // ES5  
    let arr = str.split('');
    // ES6  
    let arr = [...str];  
    // [ "h", "e", "l", "l", "o" ]  

更新对象

有点像Object.assign
需要注意这不是ES6的规范,如果你要使用这种方法,可能需要安装额外的babel插件(babel-plugin-transform-object-rest-spread)

    let a = {a: 'a', b: 'b'};
    let b = {b: 'xx'};
    console.log({...a, ...b})//{a: "a", b: "xx"}
    console.log({...a, b:'yy'})//{a: "a", b: "yy"}
    console.log(a)//{a: 'a', b: 'b'}
    console.log(b)//{b: 'xx'}

在react中的使用

把className以外的所有属性传递给元素

class AutoloadingPostsGrid extends React.Component {
    render() {
        var {
            className,
            ...others,  // contains all properties of this.props except for className
        } = this.props;
        return (
            <div className={className}>
                <PostsGrid {...others} />
                <button onClick={this.handleLoadMoreClick}>Load more</button>
            </div>
        );
    }
}

传递所有属性的同时,用新的className值覆盖

<div {...this.props} className="override">
    …
</div>

如果props中没有包含className,则使用默认的值(base),而如果props中已经包含了,则使用props中的className

<div className="base" {...this.props}>
    …
</div>

合并store

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return { ...state, visibilityFilter: action.filter }
    default:
      return state
  }
}

函数的返回值

JavaScript 的函数只能返回一个值,如果需要返回多个值,只能返回数组或对象。
扩展运算符提供了解决这个问题的一种变通方法。


    var dateFields = readDateFields(database);  
    var d = new Date(...dateFields);  
    
    上面代码从数据库取出一行数据,通过扩展运算符,直接将其传入构造函数Date。

正确识别 32 位的 Unicode 字符。

    'x\uD83D\uDE80y'.length // 4  
    [...'x\uD83D\uDE80y'].length // 3  

上面代码的第一种写法, JavaScript 会将 32 位 Unicode 字符,识别为 2 个字符,采用扩展运算符就没有这个问题。
因此,正确返回字符串长度的函数,可以像下面这样写。


    function length(str) {  
    return [...str].length;  
    }  
    length('x\uD83D\uDE80y') // 3  

凡是涉及到操作 32 位 Unicode 字符的函数,都有这个问题。因此,最好都用扩展运算符改写。



    let str = 'x\uD83D\uDE80y';  
    str.split('').reverse().join('')  
    // 'y\uDE80\uD83Dx'  
    [...str].reverse().join('')  
    // 'y\uD83D\uDE80x'  

上面代码中,如果不用扩展运算符,字符串的reverse操作就不正确。

实现 Iterator 接口的对象

任何 Iterator 接口的对象,都可以用扩展运算符转为真正的数组。

    var nodeList = document.querySelectorAll('div');  
    var array = [...nodeList];  

上面代码中,querySelectorAll方法返回的是一个nodeList对象。
它不是数组,而是一个类似数组的对象。
这时,扩展运算符可以将其转为真正的数组,原因就在于NodeList对象实现了 Iterator 接口。

对于那些没有部署 Iterator 接口的类似数组的对象,扩展运算符就无法将其转为真正的数组。


    let arrayLike = {  
    '0': 'a',  
    '1': 'b',  
    '2': 'c',  
    length: 3  
    };  
    // TypeError: Cannot spread non-iterable object.  
    let arr = [...arrayLike];  

上面代码中,arrayLike是一个类似数组的对象,但是没有部署 Iterator 接口,扩展运算符就会报错。
这时,可以改为使用Array.from方法将arrayLike转为真正的数组。

Map 和 Set 结构, Generator 函数

扩展运算符内部调用的是数据结构的 Iterator 接口,因此只要具有 Iterator 接口的对象,都可以使用扩展运算符,比如 Map 结构。

    let map = new Map([  
    [1, 'one'],  
    [2, 'two'],  
    [3, 'three'],  
    ]);  
    let arr = [...map.keys()]; // [1, 2, 3]  

Generator 函数运行后,返回一个遍历器对象,因此也可以使用扩展运算符。

    var go = function*(){  
    yield 1;  
    yield 2;  
    yield 3;  
    };  
    [...go()] // [1, 2, 3]  

上面代码中,变量go是一个 Generator 函数,执行后返回的是一个遍历器对象,对这个遍历器对象执行扩展运算符,就会将内部遍历得到的值,转为一个数组。
如果对没有iterator接口的对象,使用扩展运算符,将会报错。



    var obj = {a: 1, b: 2};  
    let arr = [...obj]; // TypeError: Cannot spread non-iterable object  

转载于:https://www.cnblogs.com/qingmingsang/articles/6438216.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值