前言
JavaScript 在越来越多的地方被使用,而且它还时不时的更新。既然更新了,就会有新的功能和新的方法来实现某些编程目标,在这里把平常常用的一些方法和技巧收藏在这里,以供以后可以直接使用
1. Set Object
Set对象是JavaScript中的一种新的对象类型,可以用来创建没有重复的数组。当你想拥有一个唯一值的列表时,这很有用。
let arr = ["a", "a", "a", "b", "b", "c"]
let withSet = [...new Set(array)]
// withSet -> ["a", "b", "c"]
当唯一值很重要的时候,我个人已经用过几次了。语法很容易记住,而且Set还有更多的功能,比如.has()函数可以检查Set是否有特定的值。
2. ?操作符
?操作符或可选的链式运算符是一个很有用的运算符,用于检查一个值是否已经被设置,当它被设置后再继续。
if(data && data.subdata && data.subdata.name === "cool") {
console.log("hi")
}
// Is the same as
if(data?.subdata?.name === "cool") {
console.log("hi")
}
我已经写了无穷无尽的if语句来检查一个值是否被设置过,这肯定会帮助解决这个问题
3. ??操作符
??操作符是一个检查一条语句左值是否为空的操作符,如果为真,它将返回右边的值。
const x = null ?? 'string';
// x: "string"
const y = 12 ?? 42;
// y: 12
当空值检查或返回一个尚未加载的字符串时,这可能非常有用。
4.精确判断数据类型
const toString = Object.prototype.toString;
/**
* @private
* @params {*} value the value to query.
* @returns { string } returns the `toStringTag`
*/
function getTag(value) {
if(value == null){
return value === undefined ? '[object Undefined]':'[object Null]'
}
return toString.call(value)
}
export {getTag};
console.log(getTag(123)); // [object Number]
console.log(getTag('123')); // [object String]
console.log(getTag(undefined)); //[object Undefined]
console.log(getTag(true)); // [object Boolean]
console.log(getTag({})); // [object Object]
console.log(getTag([])); // [object Array]
console.log(getTag(function(){})); // [object Function]
console.log(getTag(null)); // [[object Null]]
5、数组去重
// 数组去重
const arr = [{name:"小明",age:"17"},{name:"小明",age:"17"}, {name:"小明",age:20},{name:"小黄",age:17}];
const uniqyue1 = arr=>{
let len =arr.length;
for(let i=0;i<len;i++){
for(let j=i+1;j<len;j++){
if(arr[i].name==arr[j].name){
arr.splice(j,1)
len--;
j--
}
}
}
return arr
}
console.log(uniqyue1(arr))
// [{name: "小明", age: "17"},{name: "小黄", age: 17}]
```