业务需求中用到的JS技巧(持续更新)

96 阅读2分钟

前言

已经正式工作快一个月了,今天呢分享一些日常使用的JS小技巧,想到啥写啥,顺便记忆一下

正文

合并两个对象数组

 let arr=[]
 arr = arr1.map((item, index) => {
     return { ...item, ...arr2[index] }
 })

根据相同的id(某个属性值),合并两个数组对象

 let arr=[]
 arr = arr1.map((item, index) => {
     const data = arr2.find(i => i.id === item.id)
     return { ...item, ...data }
 })

数组对象去重

方法一
 uniqueArr(arr, prop) {
     const obj = {}
     const tempArr = []
     for (const item of arr) {
         if (!obj[item[prop]]) {
             tempArr.push(item)
             obj[item[prop]] = true
         }
     }
     return tempArr
 },
方法二
 const res = new Map()
 return arr.filter(item => !res.has(item[prop]) && res.set(item[prop], 1))

Set去重

 const Arr = new Set([arr]) //只能去重基本数据数组
 Array.from(Arr)  //去重之后要转回数组对象

Object.keys

 const obj = {
     id:1,
     pname:'小米',
     price:1999,
     num:2000
 };
 console.log(Object.keys(obj))     //['id', 'pname', 'price', 'num']
 Object.key(obj).length          //可以判断是否有得到对应的对象属性
 ​
 // 传入字符串,返回索引值
 let str = "Beijing"; 
 console.log(Object.keys(str))    // ["0", "1", "2", "3", "4", "5", "6"]
 ​
 // 传入数组,返回索引值
 let arr = ["a", "b", "c"];
 console.log(Object.keys(arr))       //["0", "1", "2"]

Object.values

 let obj = {
     foo : "bar",
     baz : 20
 };
 console.log(Object.values(obj));  // ["bar", 20]
 ​
 const obj = {100 : "a", 2 : "b", 7 : "c"};
 console.log(Object.values(obj));   //["b", "c", "a"]
 //属性名为数值的属性,是按照数值大小,从小到大遍历的,因此返回的顺序是b、c、a。
 //Object.values会过滤属性名为 Symbol 值的属性

vue游览器错误

获取可能没有值的数组

如果我们不过Array一个默认值就会报错,因为Array可能匹配不到,还有一些类似的场景,就需要返回一个数组的场景,这只是其中的一种情况。

 const messageContentTemp = ''
 const matchReg = /e/g
 var reg = RegExp(matchReg)
 // const Array = messageContentTemp.match(reg)  //错误
 const Array = messageContentTemp.match(reg) || []  //正确
 for (const i of Array) {
     console.log(i)
 }

image.png image.png

也会出现一种情况,我们拿到变量,我们知道是数组,但是变量可能是undefined、null

 const row = undefined // null
 // const content = row.length && row  //错误
 const content = row?.length && row || []  //正确

image.png

JSON.parse转换

后端返回or我们传入JSON格式的对象,我们需要转换成对象,如果我们要使用对象中的属性,我们需要提前判断,给予默认值

 const row = '{}'
 //const content = row && JSON.parse(row.content) || {}  //错误
 const content = row.content && JSON.parse(row.content) || {} //正确
 const { pictureList = [], richTextList = [] } = content
 console.log(pictureList, richTextList)

image.png image.png

另一种错误

 const row = undefined
 //const content = row.content && JSON.parse(row.content) || {}  //错误
 const content = row?.content && JSON.parse(row.content) || {} //正确
 const { pictureList = [], richTextList = [] } = content
 console.log(pictureList, richTextList)

image.png image.png

最后

有遇到新的就会更新