【面试】ES6语法大赏

538 阅读1分钟

1. let和const

在ES6中增加了两个关键字:letconst,都可以用于定义变量。

  • let:基本上可以替代var的作用。使用var会出现变量提升的现象,即第5行代码使用了第10行定义的变量且不会报错。在let定义下的变量不允许出现这种现象。
  • const:可以被认为是常量定义,一旦被const定义后就不可改变。

2. 解构赋值

数组:

let [name = 2, age = 1];
// name: 2
// age: 1

对象:

let {name, age} = {
    name: 'Him',
    age: Infinity,
};

函数默认值:

let add = ([x, y] = [1, 2]) => {
    return x + y;
};

console.log(add()); // 输出3

3. 基本数据类型

3.1 字符串

多行字符串:

let str = `
    日破云涛万里红。
`;

模板字符串:

let num = '万';

let str = `日破云涛${num}里红`;

3.2 数组三点语法

作用:数组脱壳,变成n个元素(n是数组长度)。

let sorted = (...arr) => {
    return arr.sort();
};

3.3 箭头函数

例:

let sumOfTwo = (a, b) => { return a + b; };

注意:箭头函数不能挂载到Function的原型链!

3.4 对象中函数的简写

例:

let obj = {
    rem: function() {
        console.log('Graduation');
    },
}

等价写法如下:

let obj = {
    rem() {
        console.log('Graduation');
    },
}

4. 类的写法

ES6之后,JavaScript的类写法和其他语言(Java)越来越像了。

例1:

class TreeNode{
    // 构造函数。相当于Python的__init__魔法方法
    constructor(value){
        this.value = value;
        this.left = undefined;
        this.right = undefined;
    }
}

// 二叉树类
class BinaryTree{
    // 构造函数。下面会调用TreeNode类,演示调用方法
    constructor(node = undefined){
        this.root = node;
    }
    
    // 广度优先添加节点
    addNode(item) {
        if(this.root === undefined){
            this.root = new TreeNode(item);
        }else {
            let queue = [];
            queue.push(this.root);
            
            while(queue.length > 0){
                let node = queue.shift(); // 从队列中取出第一个节点
                
                // 判断左节点是否为空
                if(node.left === undefined){
                    node.left = new TreeNode(item);
                    return ;
                }else {
                    queue.push(node.left);
                }
                
                if(node.right === undefined){
                    node.right = new TreeNode(item);
                    return ;
                }else {
                    queue.push(node.right);
                }
            }
        }
    }
}