关于前端:ES6数组1扩展运算符

32次阅读

共计 1772 个字符,预计需要花费 5 分钟才能阅读完成。

此文为学习笔记,参考 ES6 入门 - 数组的扩大(阮一峰)

扩大运算符

含意

扩大运算符(spread)是三个点(…),把数组转换为逗号分隔的参数序列。

console.log([1, 2, ...[3, 4, 5], 6]);    //[1,2,3,4,5,6]

次要使用于函数调用
用于形参:

function push(array, ...items) {array.push(...items)
}
let a1 = [1, 2];
push(a1, 3, 4, 5);
console.log(a1);    //[1, 2, 3, 4, 5]

用于实参:

function add(x, y, z) {return x + y + z;}
console.log(add(...[1, 2, 3]));    //6

扩大运算符和失常的函数参数能够联合应用

function f(a, b, c, d, e) {console.log(...arguments);    //1,2,3,4,5
}
const arry = [2, 3];
f(1, ...arry, 4, ...[5])

扩大运算符前面还能够应用表达式

let odd = true;
const arry = [...(odd ? [1, 3, 5] : [2, 4, 6]), 10];    //[1, 3, 5, 10]

⚠️留神:只有函数调用时,扩大运算符才能够放在圆括号里,否则会报错。

console.log((...[1, 2]));
//Uncaught SyntaxError: Unexpected token '...'
console.log(...[1, 2])
//1 2

代替函数的 apply()办法

代替 apply

es6 之前如果须要将数组转成函数的参数,会应用 apply()办法

function add(a, b, c) {return a + b + c;}
var arr = [3, 4, 5];
add.apply(null, arr); // ES5 的写法

add(...arr); //ES6 的写法

理论样例 1

Math.max.apply(null, [5, 51, 54, 3, 1]); // ES5 的写法

Math.max(...[5, 51, 54, 3, 1]); // ES6 的写法

样例 2

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

Array.prototype.push.apply(arr1, arr2); //ES5 的写法

arr1.push(...arr2); //ES6 的写法
Function.prototype.apply()

在这,补充一下对于 apply()源码手写

apply()办法 ES3 版

实现 es3apply

Function.prototype.es3apply = function (context, arr) {
    var target = context || window;
    target.fn = this;
    var result;
    if (!arr) {result = target.fn();
    } else {var args = [];
        for (let i = 0; i < arr.length; i++) {args.push('arr[' + i + ']');
        }
        result = eval('target.fn(' + args + ')');
    }
    return result;
}

利用样例

function Project() {
    return {
        type: 'PRD',
        path: 'https://domain-prd.com',
        getPath: function () {return this.path}
    }
}

var envDev = {
    type: 'DEV',
    path: 'http://127.0.0.1:8080'
}

var myPro = new Project();

console.log(myPro.getPath());   //https://domain-prd.com

console.log(myPro.getPath.es3apply(envDev));    //http://127.0.0.1:8080
apply()办法 ES6 版
Function.prototype.es6apply = function (context, arr) {
    var target = context || window;
    target.fn = this;
    var result;
    if (!arr) {result = target.fn();
    } else {result = target.fn(...arr)
    }
    return result;
}

正文完
 0