js的那些你不知道的技巧
1. 三元表达式 与 if…else…
// if else写法
let areYouDoing = '';
if (isHoliday) {
areYouDoing = 'playing games';
} else {
areYouDoing = 'at work';
}
// if else另一种写法 优先给一个默认值
let areYouDoing = 'at work';
if (isHoliday) {
areYouDoing = 'playing games';
}
// 三元运算写法
let areYouDoing = isHoliday ? 'playing games' : 'at work';
2. 解构赋值并重命名
let obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
}
// 常规写法:
let key1 = obj.key1;
let key2 = obj.key2;
let key3 = obj.key3;
// 简写:
const { key1, key2, key3 } = obj;
// 简写并重命名key
const { key1: aliasKey, key2, key3 } = obj;
console.log(key1); // key1 is not defined
console.log(aliasKey); // 'value1'
3. 合并对象、数组
let obj1 = { a: 1, b: 2, c: 3 };
let obj2 = { aa: 11, bb: 22, cc: 33 };
// 常规写法
let allObj1 = Object.assign(obj1, obj2);
//简写
let allObj2 = { ...obj1, ...obj2 };
4. 空值合并操作符( ?? ) 与 逻辑或运算符( || )
空值合并操作符( ?? )
:仅当
左侧的操作数为null 或者 undefined
时,返回其右侧操作数,否则返回左侧操作数。逻辑或运算符( || )
: 逻辑或操作符会在左侧操作数为假值时
返回右侧操作数
示例:
const foo = null ?? 'default string';
console.log(foo); // "default string"
const baz = 0 ?? 42;
console.log(baz); // 0
5. 可选链操作符( ?. )
注意:语法太新,需考虑 【浏览器兼容问题】
// 常规写法
let obj = { doSomething: () => {} };
if (obj && obj.doSomething) {
doSomething();
}
// 简写
obj?.doSomething();
6. 使用BigInt支持大整数计算问题
// 超过 53 个二进制位的数值(相当于 16 个十进制位),无法保持精度
Math.pow(2, 53) == Math.pow(2, 53) + 1; // 2的53次幂 与 2的53次幂+1 相比较结果为 true
console.log(BigInt(1));// 1n
console.log(BigInt(Math.pow(2, 53))) // 007199254740992n
BigInt(Math.pow(2, 53)) === BigInt(Math.pow(2, 53)) + BigInt(1) // false
7. 使用Array.prototype.at()简化arr.length
at()
方法接收一个整数值并返回该索引的项目,允许正数和负数
,负整数从数组中的最后一个项目开始倒数。
let arr = [1, 2, 3, 4, 5];
// 获取数组最后一位
// 常规写法
let last1 = arr.slice(-1)[0];
let last2 = arr[arr.length - 1];
// 简写
let last3 = arr.at(-1);
8. 多变量赋值操作
// 常规写法
let a = 1, b = 2, c = 3;
// 简写
let [a, b, c] = [1, 2, 3];
9. 交换变量的值
// 常规写法
let a = 1, b = 2;
let temp = a;
a = b, b = temp;
// 简写
[a, b] = [b, a];
10. 多条件判断
// 常规写法1
if( value == 'value1' || value == 'value2' || value == 'value3') {
// do something...
}
// 常规写法2
switch(value){
case 'value1':
case 'value2':
case 'value3':
// do something
break;
}
// 简写1
if (['value1', 'value2', 'value3'].indexOf(value) >= 0) {
// do something
}
// 简写2 (推荐)
if (['value1', 'value2', 'value3'].includes(value)) {
// do something
}
11. 指数运算
一般我们使用 Math.pow() 进行指数运算,现在我们可以使用双星号 (**)
// 常规写法
console.log(Math.pow(2, 10)); // 1024
// 简写
console.log(2 ** 10); // 1024
12. 双非位运算符(~~)
双非位运算符是 Math.floor() 的替代品
// 常规写法
const floor = Math.floor(123.98) // 123
// 简写
const floor = ~~123.98 // 123
13. 找到数组中的最大/最小值
let arr = [11, 3, 1, 0, 5, 2, 6, 10];
// 常规写法
let min = arr[0], max = arr[0];
for(let i = 1; i < arr.length - 1; i++){
min = arr[i] > min ? min : arr[i] // 最小值
max = arr[i] > max ? arr[i] : max // 最大值
}
// 简写
Math.min(...arr)
Math.max(...arr)
14. 检查属性是否存在对象中
let obj = {
key: null
}
// 常规写法
Object.prototype.hasOwnProperty.call(obj, 'key');
// 简写 (注意浏览器兼容性问题)
Object.hasOwn(obj, 'key');
15. 千分位分隔符
let money = 100000000; // 1亿
money.toString().replace(/(?!^)(?=(\d{3})+$)/g, ",") // '100,000,000'
16. 妙借数组拼接字符串
let hh = 12, mm = 23, ss = 34;
let timeString = [hh, mm, ss].join(':')
// 常规写法
let timeString = `${hh}:${mm}:${ss}`;
// 优雅写法
let timeString = [hh, mm, ss].join(':')
17. 判断字符串前缀、后缀
const url = "https://www.baidu.com";
// 常规写法
const isHTTPS = /^https:\/\//.test(url); // true
const isCom= /\.com$/.test(url); // true
// 优雅写法
const isHTTPS = url.startsWith("https://") // true
const isCom = url.endsWith(".com"); // true
持续更新中。。。