• 技术文章 >web前端 >前端问答

    es6新增了哪些扩展

    青灯夜游青灯夜游2022-04-13 11:52:24原创126

    es6新增的扩展:1、允许为函数的参数设置默认值;2、新增箭头函数,可使用箭头“=>”来定义函数,语法“var 函数名=(参数)=>{...}”;3、扩展元素符“...”,可将一个数组转为用逗号分隔的参数序列,也可将某些数据结构转为数组。

    本教程操作环境:windows7系统、ECMAScript 6版、Dell G3电脑。

    es6新增的扩展

    一、函数参数

    ES6允许为函数的参数设置默认值

    function log(x, y = 'World') {
      console.log(x, y);
    }
    
    console.log('Hello') // Hello World
    console.log('Hello', 'China') // Hello China
    console.log('Hello', '') // Hello

    函数的形参是默认声明的,不能使用letconst再次声明

    function foo(x = 5) {
        let x = 1; // error
        const x = 2; // error
    }

    参数默认值可以与解构赋值的默认值结合起来使用

    function foo({x, y = 5}) {
      console.log(x, y);
    }
    
    foo({}) // undefined 5
    foo({x: 1}) // 1 5
    foo({x: 1, y: 2}) // 1 2
    foo() // TypeError: Cannot read property 'x' of undefined

    上面的foo函数,当参数为对象的时候才能进行解构,如果没有提供参数的时候,变量xy就不会生成,从而报错,这里设置默认值避免

    function foo({x, y = 5} = {}) {
      console.log(x, y);
    }
    
    foo() // undefined 5

    参数默认值应该是函数的尾参数,如果不是非尾部的参数设置默认值,实际上这个参数是没发省略的

    function f(x = 1, y) {
      return [x, y];
    }
    
    f() // [1, undefined]
    f(2) // [2, undefined]
    f(, 1) // 报错
    f(undefined, 1) // [1, 1]

    二、函数属性

    函数的length属性

    length将返回没有指定默认值的参数个数

    (function (a) {}).length // 1
    (function (a = 5) {}).length // 0
    (function (a, b, c = 5) {}).length // 2

    rest 参数也不会计入length属性

    (function(...args) {}).length // 0

    如果设置了默认值的参数不是尾参数,那么length属性也不再计入后面的参数了

    (function (a = 0, b, c) {}).length // 0
    (function (a, b = 1, c) {}).length // 1

    name属性

    返回该函数的函数名

    var f = function () {};
    
    // ES5
    f.name // ""
    
    // ES6
    f.name // "f"

    如果将一个具名函数赋值给一个变量,则 name属性都返回这个具名函数原本的名字

    const bar = function baz() {};
    bar.name // "baz"

    Function构造函数返回的函数实例,name属性的值为anonymous

    (new Function).name // "anonymous"

    bind返回的函数,name属性值会加上bound前缀

    function foo() {};
    foo.bind({}).name // "bound foo"
    
    (function(){}).bind({}).name // "bound "

    三、函数作用域

    一旦设置了参数的默认值,函数进行声明初始化时,参数会形成一个单独的作用域

    等到初始化结束,这个作用域就会消失。这种语法行为,在不设置参数默认值时,是不会出现的

    下面例子中,y=x会形成一个单独作用域,x没有被定义,所以指向全局变量x

    let x = 1;
    
    function f(y = x) { 
      // 等同于 let y = x  
      let x = 2; 
      console.log(y);
    }
    
    f() // 1

    四、严格模式

    只要函数参数使用了默认值、解构赋值、或者扩展运算符,那么函数内部就不能显式设定为严格模式,否则会报错

    // 报错
    function doSomething(a, b = a) {
      'use strict';
      // code
    }
    
    // 报错
    const doSomething = function ({a, b}) {
      'use strict';
      // code
    };
    
    // 报错
    const doSomething = (...a) => {
      'use strict';
      // code
    };
    
    const obj = {
      // 报错
      doSomething({a, b}) {
        'use strict';
        // code
      }
    };

    五、箭头函数

    使用“箭头”(=>)定义函数

    var f = v => v;
    
    // 等同于
    var f = function (v) {
      return v;
    };

    如果箭头函数不需要参数或需要多个参数,就使用一个圆括号代表参数部分

    var f = () => 5;
    // 等同于
    var f = function () { return 5 };
    
    var sum = (num1, num2) => num1 + num2;
    // 等同于
    var sum = function(num1, num2) {
      return num1 + num2;
    };

    如果箭头函数的代码块部分多于一条语句,就要使用大括号将它们括起来,并且使用return语句返回

    var sum = (num1, num2) => { return num1 + num2; }

    如果返回对象,需要加括号将对象包裹

    let getTempItem = id => ({ id: id, name: "Temp" });

    注意点:

    六、扩展运算符

    ES6通过扩展元素符...,好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列

    console.log(...[1, 2, 3])
    // 1 2 3
    
    console.log(1, ...[2, 3, 4], 5)
    // 1 2 3 4 5
    
    [...document.querySelectorAll('p')]
    // [<p>, <p>, <p>]

    主要用于函数调用的时候,将一个数组变为参数序列

    function push(array, ...items) {
      array.push(...items);
    }
    
    function add(x, y) {
      return x + y;
    }
    
    const numbers = [4, 38];
    add(...numbers) // 42

    可以将某些数据结构转为数组

    [...document.querySelectorAll('p')]

    能够更简单实现数组复制

    const a1 = [1, 2];
    const [...a2] = a1;
    // [1,2]

    数组的合并也更为简洁了

    const arr1 = ['a', 'b'];
    const arr2 = ['c'];
    const arr3 = ['d', 'e'];
    [...arr1, ...arr2, ...arr3]
    // [ 'a', 'b', 'c', 'd', 'e' ]

    注意:通过扩展运算符实现的是浅拷贝,修改了引用指向的值,会同步反映到新数组
    下面看个例子就清楚多了

    const arr1 = ['a', 'b',[1,2]];
    const arr2 = ['c'];
    const arr3  = [...arr1,...arr2]
    arr1[2][0] = 9999 // 修改arr1里面数组成员值
    console.log(arr3 ) // 影响到arr3,['a','b',[9999,2],'c']

    扩展运算符可以与解构赋值结合起来,用于生成数组

    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];
    // 报错

    可以将字符串转为真正的数组

    [...'hello']
    // [ "h", "e", "l", "l", "o" ]

    定义了遍历器(Iterator)接口的对象,都可以用扩展运算符转为真正的数组

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

    如果对没有 Iterator 接口的对象,使用扩展运算符,将会报错

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

    七、构造函数新增的方法

    关于构造函数,数组新增的方法有如下:

    Array.from()

    将两类对象转为真正的数组:类似数组的对象和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)

    let arrayLike = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        length: 3
    };
    let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

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

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

    Array.of()

    用于将一组值,转换为数组

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

    没有参数的时候,返回一个空数组
    当参数只有一个的时候,实际上是指定数组的长度
    参数个数不少于 2 个时,Array()才会返回由参数组成的新数组

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

    八、实例对象新增的方法

    关于数组实例对象新增的方法有如下:

    copyWithin()

    将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组
    参数如下:

    [1, 2, 3, 4, 5].copyWithin(0, 3) // 将从 3 号位直到数组结束的成员(4 和 5),复制到从 0 号位开始的位置,结果覆盖了原来的 1 和 2
    // [4, 5, 3, 4, 5]

    find()、findIndex()

    find()用于找出第一个符合条件的数组成员
    参数是一个回调函数,接受三个参数依次为当前的值、当前的位置和原数组

    [1, 5, 10, 15].find(function(value, index, arr) {
      return value > 9;
    }) // 10

    findIndex返回第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1

    [1, 5, 10, 15].findIndex(function(value, index, arr) {
      return value > 9;
    }) // 2

    这两个方法都可以接受第二个参数,用来绑定回调函数的this对象。

    function f(v){
      return v > this.age;
    }
    let person = {name: 'John', age: 20};
    [10, 12, 26, 15].find(f, person);    // 26

    fill()

    使用给定值,填充一个数组

    ['a', 'b', 'c'].fill(7)
    // [7, 7, 7]
    
    new Array(3).fill(7)
    // [7, 7, 7]

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

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

    注意,如果填充的类型为对象,则是浅拷贝

    entries(),keys(),values()

    keys()是对键名的遍历、values()是对键值的遍历,entries()是对键值对的遍历

    or (let index of ['a', 'b'].keys()) {
      console.log(index);
    }
    // 0
    // 1
    
    for (let elem of ['a', 'b'].values()) {
      console.log(elem);
    }
    // 'a'
    // 'b'
    
    for (let [index, elem] of ['a', 'b'].entries()) {
      console.log(index, elem);
    }
    // 0 "a"

    includes()

    用于判断数组是否包含给定的值

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

    方法的第二个参数表示搜索的起始位置,默认为0
    参数为负数则表示倒数的位置

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

    flat(),flatMap()

    将数组扁平化处理,返回一个新数组,对原数据没有影响

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

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

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

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

    // 相当于 [[2, 4], [3, 6], [4, 8]].flat()
    [2, 3, 4].flatMap((x) => [x, x * 2])
    // [2, 4, 3, 6, 4, 8]

    flatMap()方法还可以有第二个参数,用来绑定遍历函数里面的this

    九、数组的空位

    数组的空位指,数组的某一个位置没有任何值

    ES6 则是明确将空位转为undefined,包括Array.from、扩展运算符、copyWithin()、fill()、entries()、keys()、values()、find()和findIndex()

    建议大家在日常书写中,避免出现空位

    十、排序稳定性

    将sort()默认设置为稳定的排序算法

    const arr = [
      'peach',
      'straw',
      'apple',
      'spork'
    ];
    
    const stableSorting = (s1, s2) => {
      if (s1[0] < s2[0]) return -1;
      return 1;
    };
    
    arr.sort(stableSorting)
    // ["apple", "peach", "straw", "spork"]

    排序结果中,straw在spork的前面,跟原始顺序一致

    以上就是es6新增了哪些扩展的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:es6 新增扩展
    上一篇:caption是html5新增的吗 下一篇:css3中flex值为1是什么意思
    Web大前端开发直播班

    相关文章推荐

    • es6新增的声明方法有什么• es6的class有没有变量提升• es6怎么检测数组中有没有某个元素• es5和es6作用域的区别是什么• es6怎么判断对象有没有某属性• es6怎么判断一个变量是否为字符串

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网