这是我参与更文挑战的第16天,活动详情查看 更文挑战
为了能有更多摸鱼的时间,准备写一个js技巧系列,主要就是总结一些可以提高开发速度和效率的js小窍门。
从数组中删除重复
const array = [1, 3, 2, 3, 2, 'Axjy', true, false, true, 'Axjy', 1, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray)
原理:set只允许存储不重复的值,所以当你放入一个数组,它会自动去掉重复的值。
更简洁的For循环
const names = ['Axjy','Jin','olivivian']
for(let i = 0;i<names.length;i++){
const name = names[i]
console.log(name)
}
等同于
for(let name of names) console.log(name)
空值合并运算符(??)
可以用来保证值不为 null 或者 undefined
注:(??) 不要直接和 AND(&&)和 OR(||)一起用
可选链操作符(?.)
当尝试访问可能不存在的对象属性时,可选链操作符将会使表达式更短、更简明。
原本访问name前我们需要先判断employee是否存在需要这样做
let result = user.employee && user.employee.name;
现在只需要
let result = user.employee?.name
通过使用 ?. 操作符取代 . 操作符,JavaScript 会在尝试访问 user.employee.name 之前,
先隐式地检查并确定 user.employee 既不是 null 也不是 undefined。
减少嵌套 if..else 或 switch case
function doSomething(){ console.log('执行方法') }
需求一:如果满足某个条件,执行方法
let a = 6
if(a===6){ doSomething()}
//等同于
a===6 && doSomething()
需求二:如果不满足某个条件,执行方法
function doSomething(){
console.log('执行方法')
}
let a = 6
if(a !== 5){ doSomething()}
//等同于
a===5 || doSomething()
快速合并对象
const result = {...arr1, ...arr2, ...arr3}
数组解构交换值
数组求和,最大值,最小值
const array = [5,4,7,8,9,2];
//求和
array.reduce((a,b) => a+b);
//最大值
array.reduce((a,b) => a>b?a:b);
//最小值
array.reduce((a,b) => a<b?a:b);
字符串和数字快速互转(不推荐)
这个方法仅用于了解,但是考虑到代码的可读性,不推荐使用;
let num = 12
let numString = num + "";
let stringNum = + numString;
console.log('数字转字符串',numString,typeof numString)
console.log('字符串转数字',stringNum,typeof stringNum)
原理:数字加空字符串,变为字符串;字符串使用加号(+)转为数字。
小可爱看完就点个赞再走吧!🤞🤞🤞