数组扁平化

function flatten(arr) {
    let result = [];

    for (let i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]));
        } else {
            result = result.concat(arr[i]);
        }
    }

    return result;
}

const a = [1, [2, [3, 4]]];
console.log(flatten(a));

prototype 实现继承

function Foo(name) {
    this.name = name;
}

Foo.prototype.myName = function () {
    return this.name;
}

// 继承属性,通过借用构造函数调用
function Bar(name, label) {
    Foo.call(this, name);
    this.label = label;
}

// 继承方法,创建备份
Bar.prototype = Object.create(Foo.prototype);

// 必须设置回正确的构造函数,要不然在会发生判断类型出错
Bar.prototype.constructor = Bar;

// 必须在上一步之后
Bar.prototype.myLabel = function () {
    return this.label;
}

var a = new Bar("a", "obj a");

a.myName(); // "a"
a.myLabel(); // "obj a"

获取 URL 参数

function getQueryVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

Promise 原理

class MyPromise {
    constructor(fn) {
        this.resolvedCallbacks = [];
        this.rejectedCallbacks = [];

        this.state = 'PENDING';
        this.value = '';

        fn(this.resolve.bind(this), this.reject.bind(this));
    }

    resolve(value) {
        if (this.state === 'PENDING') {
            this.state = 'RESOLVED';
            this.value = value;

            this.resolvedCallbacks.map(cb => cb(value));
        }
    }

    reject(value) {
        if (this.state === 'PENDING') {
            this.state = 'REJECTED';
            this.value = value;

            this.rejectedCallbacks.map(cb => cb(value));
        }
    }

    then(onFulfilled, onRejected) {
        if (this.state === 'PENDING') {
            this.resolvedCallbacks.push(onFulfilled);
            this.rejectedCallbacks.push(onRejected);
        }

        if (this.state === 'RESOLVED') {
            onFulfilled(this.value);
        }

        if (this.state === 'REJECTED') {
            onRejected(this.value);
        }
    }
}