短小精悍的JS(LTS)
Previsously on the short of JS long-term support:
主要总结一些容易忽略的比较小的点
1.慎用==
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Equality
console.log(typeof NaN);
console.log(['1', '2', '3'].map(parseInt));
console.log(-0 === 0); // true
console.log(typeof null); // object
console.log(typeof undefined); // undefined
console.log([100] == 100) // true
console.log(null == undefined) // true
console.log(Number(NaN)); // number NaN noa a number is a type of number
2.检查属性是否存在于对象中
const obj = {
id: 1,
name: 'bing'
};
console.log('id' in obj) // true
console.log('id2' in obj) // false
3.使用加号运算符将字符串转为数字
const str = "123";
console.log(typeof +str); // number
4.使用slice和padStart掩码数字
const str = "123";
console.log(typeof +str); // number
console.log(str.padStart(4, '*')); // 4包含总长度 *123
5.动态添加属性
const foo = {}
let index = 2;
obj[key] = 'bar'
6.非空判断(空值合并运算符)
?? 空值合并运算符
当运算符左边为nullish(null 或 undefined 则返回右边的值)
const fn = (para) => {
if ((para ?? '') !== '') {
console.log("para is not null or undefined or ''");
}
}
console.log(fn('')); // undefined
console.log(fn(null));// undefined
console.log(fn(undefined));//undefined;
fn(2334) // para is not null or undefined or ''
7.有条件地为对象添加属性
// 没工资的给你们发工资啦
const noSalary = true;
const foo = {
id:1,
...(noSlary && {salary: 5000})
}
8.JSON的多参数
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
// 工资翻倍啦
const obj = {
id: 123,
salary: 5000
}
const obj1 = JSON.stringify(obj, (key, value) => {
return key === 'salary' ? value * 2 : value
})
console.log(JSON.parse(obj1)); //{ id: 123, salary: 10000 }
9.fathy值的过滤
const arr = [false,null,undefined,0,+0,-0,NaN,'',666,'2333'];
console.log(arr.filter(Boolean)) // [ 666, '2333' ]
10.解构赋值
注意
1.解构的对象不能为null 或 undefined
2.合并对象时,后者会覆盖前者同名属性
//解构虽好,可不要贪杯哦
const obj = {
id:123,
name:'bing'
}
const {id,name} = obj;
console.log(id,name)
//不能为null 或者 undefined
const {id2} = null || {};
console.log(id2);
const obj1 = {
id:1,
name:'bing'
}
const obj2 ={
id:2,
name: 'bing2'
}
const obj3 = {...obj1,...obj2};
console.log(obj3);
11.避免set的无限递归
const set = new Set(1)
set.forEach( item => {
set.delete(1)
set.add(1)
})
// 先删除集合元素1,又添加1,会造成无限递归
//修正如下
const set = new Set(1)
const newSet = new Set(set)
newSet.forEach( item => {
set.delete(1)
set.add(1)
})