javaScript经常使用到的方法

判断一个对象是否为空对象,不为null,仅仅是{};可使用以下方法判断:

if (JSON.stringify(object) === '{}') {
    //..
}
//也能够
if (Object.keys(object).length === 0) {
    // ..
}

数组去重:

let list = []
[1, 2, 2, 3].forEach(e => {
    if (!list.includes(e)) list.push(e)
})
/* 或者 */
let newArr = Array.from(new Set([1, 2, 2, 3]));
console.log(newArr) //[1, 2, 3]

/* set也能够对字符串去重 */
let newString = [...new Set('aabbcc')].join('');
console.log(newString) // abc

/* 多个数组一块儿去重 */
let arr1 = [1, 2, 3];
let arr2 = [2, 3, 4];
let newArr = Array.from(new Set([...arr1, ...arr2]));
console.log(newArr) // [1, 2, 3, 4]

判断数据类型

let judgeObj = ['a', 100, true, undefined, NaN, {a: 1}, [1], null, function(){}]
judgeObj.forEach(e => {
    console.log(Object.prototype.toString.call(e))
})
//结果为:
[object String], [object Number], [object Boolean], [object.Undefined], [object.Number], [object Object], [object Null], [object Function]
//这个方法基本能够一劳永逸的解决typeof instanceof Array.isArray所带来的不肯定性
相关文章
相关标签/搜索