js开发技巧

78 阅读1分钟

数组去重

const arr = ['a','b','c','a','b']; 
const newArr = [...new Set(arr)];

Array.from + Set 去重

const arr = ['a','b','c','a','b']; 
const newArr = Array.from(new Set(arr));

Array.from 方法就是将一个类数组对象(array-like object)或者可遍历对象(包括 ES6 新增的数据结构 Set 和 Map)转换成一个真正的数组,下面样例常用来mock数据。

new Array(10).fill(""); // (10) ['', '', '', '', '', '', '', '', '', '']

Array.from(new Array(10).keys()); // (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.from({ length: 10 }, (v, i) => i); // (10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

类型检测

typeof 可以检测一些基本的数据类型,正则、Date、{ }、[ ]、null 等 输出结果为都为 object

console.log(typeof /\d/); //object
console.log(typeof new Date()); //object
console.log(typeof {}); //object
console.log(typeof []); //object
console.log(typeof null); //object
console.log(typeof new Map()); //object
console.log(typeof 123); //number
console.log(typeof true); //boolean
console.log(typeof function () {}); //function
console.log(typeof undefined); //undefined

instanceof 用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。

function Foo() {}
let f = new Foo();
console.log(f instanceof Foo); // true
console.log(Foo instanceof Object); //true

let arr = [1, 2, 3, 4];
console.log(arr instanceof Array); //true

new Date() instanceof Object; // true
new Date() instanceof Date; // true

以上两种方法有其局限性,推荐使用下面判断数据类型方法

function judgeType(data) {
  return Object.prototype.toString
    .call(data)
    .replace(/\[object (\w+)\]/, "$1")
    .toLowerCase();
}

检查是否为空对象

Object.keys({}).length // 0 
JSON.stringify({}) === '{}';