1. 生成随机数
在日常开发中,生成随机数是非常常见的需求。但是我可以一句代码就能搞定,示例如下:
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random(1, 100)); // 输出 1 到 100 之间的随机整数
解析:代码核心是 Math.random(),它生成一个 0 到 1 的随机数。通过数学公式将其映射到指定范围,并利用 Math.floor() 确保返回的是整数。
2. 数组去重
const unique = (arr) => [...new Set(arr)];
console.log(unique([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
解析:Set 是一种集合类型,能自动去重。而 ... 是扩展运算符,可以将 Set 转换为数组,省去手动遍历的步骤。
3. 检查变量类型
const type = (value) => Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
` console.log(type(123)); // 'number'
console.log(type([])); // 'array'
console.log(type(null)); // 'null'
**解析**:通过 Object.prototype.toString 可以准确获取变量的类型信息,而 slice(8, -1) 是为了提取出 [object Type] 中的 Type` 部分。
4. 深拷贝对象
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
const obj = { a: 1, b: { c: 2 } };
const copy = deepClone(obj);
console.log(copy); // { a: 1, b: { c: 2 } }
注意:这种方法不适用于循环引用的对象。如果需要处理复杂对象,建议使用 Lodash 等库。
5. 交换两个变量的值
日常中,如果是传统写法,可能会采用需要引入临时变量,但是,今天,我可以教你一个新写法,使用解构赋值就简单多了:
let a = 1, b = 2; [a, b] = [b, a];
` console.log(a, b); // 2, 1
` 解析:利用 ES6 的解构赋值语法,可以轻松实现两个变量的值交换,代码简洁且直观。