记在实战项目中对于数组和对象的优雅处理

180 阅读3分钟

这是我参与更文挑战的第4天,活动详情查看: 更文挑战

关于对象的一些操作

  1. for...in循环对象的一些事。
const marven = { age: 20 }
//如何遍历marven对象获取下面的属性?

for(const key in marven) {
    console.log(`${key}: ${marven[key]} in marven`)
}
// age: 20 in marven

for...in可以遍历对象的同时也会遍历对象的原型链,如果只想遍历对象本身,可以按以下代码操作。

Object.prototype.name = 'Kev1nzh'
const marven = { age: 20 }

for(const key in marven) {
    console.log(`${key}: ${marven[key]} in marven`)
}
// age: 20 in marven
// name: 12033 in Kev1nzh 但是name属性不存在于marven对象本身。


for(const key in marven) {
    if(marven.hasOwnProperty(key)) {
        console.log(`${key}: ${marven[key]} in marven`)
    }
}
// age: 20 in marven 只输出对象本身的age属性了。

但对于我这种强迫症,少一层嵌套我就爽一分。

Object.keys(marven).forEach(key => {
    console.log(`${key}: ${marven[key]} in marven`)
})
// age: 20 in marven 耶 舒服

关于数组的一些操作

  1. filteres5中的语法,对于处理筛选业务代码时,它就是yyds。
//假设input输入后,前端筛选数据。
<input [(ngModel)]="filterData.name" (ngModelChange)="filterName()" /> 

<div *ngFor="left item of list">{{item.name}}</div>
function filterName () {
    const {name} = filterData
    const filteredList = backupList.filter(
        i => i.name.toLocaleLowerCase().includes(name.toLocaleLowerCase())
    )
}

// yyds的神,几行代码就能解决简单的筛选功能。

2.还是filter,有时候用来确定最后产出的数组元素有没有值。比如以下代码。

async function resolvePlugins(...){
    //....做了一大堆事情 
    
    return [
        ...cssPostPlugin,
        ...postPlugins,
        ...buildPlugins,
    ].filter(Boolean)
}
// 当有自定义传入的参数时,不需要保证每个元素都有值也能运行,那就最后用filter筛选,将没有值的元素都筛走。
  1. 数组去重这个老生长谈的东西,ECMAScript 2019中的flat恰好能完美解决。
let array = [1,2,3,4,4,4,3,1,6]

// (1)利用indexOf或者双循环来解决去重(代码略过)

// (2) new Set ()
Array.from(new Set(array))  //[1, 2, 3, 4, 6] 但是解决不了多层的数组去重。

// (3) Array.prototyoe.flat 扁平化多维数组的方法 可以传入参数解构深度 默认值为1 
let array = [1,2,3,4,5,4,4,3,2,[2,3,4,2,[3,2,1,3]]]

Array.from(new Set(array.flat(Infinity))) // [1,2,3,4,5]

// 解构后再使用Set去重,完美解决多维数组。

4.对于筛选后列表高亮的处理。

有些需求筛选某段文字内的关键词,显示筛选后的结果同时也要把筛选的关键字高亮,那么我们这样做。

async filterHighight(word: string): void {
    //包含word关键词的文章list
    const filteredList: {id: number, article: string} []= getFilteredList(word)
    const highlightList = {id: number, articleGroup: string } [] = filteredList.map(({id, article}) => {
        return {
            articleGroup: article.split(word).join(`<span class="highlight" >${word}</span>`),
            id
        }
    })
    
    this.list = highlightList
}

然后在页面上直接使用渲染HTML的方法。就可以带上高亮样式啦。

  1. 获取列表里点击量最高的列表元素。
const maxCount = list.map(i => i.count).reduce((pre, cur) => {
    return Math.max(pre, cur)
})
const maxItem = list.find(i => i.count === maxCount)

打完收工。

最后

上面的这些方法基本上都是在项目中用到的,如果有更优化的方案或者新的方法可以在下面评论留言哦。

好哥哥学到的话点个赞再走吧。

另外推荐下新写的Vite源码解析,点我本站跳转

查看线上文档体验更佳 查看文档 Powered by dumi

看完有帮助的可以进入github给我一个🌟小星星 谢谢!