编辑代码

// 1、typeof能判断哪些类型
// string number boolean undefined symbol bigint object
console.log(typeof 1); // number
console.log(typeof '1'); // string
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof Symbol()); // symbol
console.log(typeof BigInt(1)); // bigint


// 2、何时使用===和==
判断值和类型是否相等时,使用===
判断值是否相等时,使用==


// 3、window.onload和DOMContentLoaded
window.onload指的是文档和图片等资源全部加载完才执行
DOMContentLoaded指的是DOM加载解析完就执行


// 4、js创建10个button,点击时弹出对应序号
const oBody = document.getElementsByTagName('body')[0];
// es6块级作用域
for (let i = 0; i < 10; i++) {
    const oButton = document.createElement('button');
    oButton.innerText = i;
    oButton.onclick = function () {
        alert(i);
    }
    oBody.appendChild(oButton);
}
// es5闭包
for (var i = 0; i < 10; i++) {
    ((i) => {
        const oButton = document.createElement('button');
        oButton.innerText = i;
        oButton.onclick = function () {
            alert(i);
        }
        oBody.appendChild(oButton);
    })(i);
}


// 5、实现debounce和throttle
function debounce (fn, wait = 1000) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        let result;
        timer = setTimeout(() => {
            result = fn.apply(this, args);
        }, wait);

        while (!result) {
            continue;
        }
        return result;
    }
}

function throttle (fn, wait = 1000) {
    let previous = 0;
    return function (...args) {
        const now = +new Date();
        if (now - previous > wait) {
            fn.apply(this, args);
            previous = now;
        }
    }
}

// 6、promise解决了什么问题
解决了异步无限回调地狱的问题,类似如下代码
ajax('/userlist', (data) => {
    ajax('/user/' + data[0].id, (data) => {
        ajax('/user/comments/' + data.commentId, (data) => {
            ajax('/user/comment/' + data[0].id, (data) => {
                // ...
            })
        })
    })
})
// promise就显得优雅很多
ajax('/userlist').then((data) => {
    return ajax('/user/' + data[0].id)
}).then((data) => {
    return ajax('/user/comments/' + data.commentId)
}).then((data) => {
    return ajax('/user/comment/' + data[0].id)
})