作为一个合格的前端老油子偷懒是必考科目,如何提高效率,利用最少的时间完成最多的工作,写最少的代码完成最多的功能,下面就整理了几个比较有意思的前端开发技巧

es6特性

array

创建数组并填充

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
new Array(2).fill(1)
// [1,1]
new Array(2).fill({})
// [{},{}]
new Array(2).fill({name:'古天乐'})
// [{name:'古天乐'},{name:'古天乐'}]

// 快速创建1到n的数组
[...new Array(n+1).keys()].slice(1,n+1)
// [1,2,3,4,·····n]
[...new Array(100).keys()].map(i=>i+1)
// [1,2,3,4,·····n]
new Array(100).fill(0).map((i,index)=> index+1)
// [1,2,3,4,·····n]
Array.from(Array(100),(i,index)=>index+1)
// [1,2,3,4,·····n]

数组求和

1
2
3
4
5
6
7
8
9
10
[1, 2, 3].reduce(function (sum, current) {
return sum + current;
}, 0);
// 6

// 对象数组求和
[{price:1},{price:2},{price:3}].reduce(function (sum, current) {
return sum + current.price;
}, 0);
// 6

数组排序

1
2
3
4
5
6
7
8
9
10
11
[4, 3, 2, 1].sort((a, b) => a - b)
// [1, 2, 3, 4]
[1, 2, 3, 4].sort((a, b) => b - a)
// [4, 3, 2, 1]

// 对象数组排序
[{price:1},{price:2},{price:3}].sort((a, b) => a.price - b.price)
// [{price:1},{price:2},{price:3}]
[{price:1},{price:2},{price:3}].sort((a, b) => b.price - a.price)
// [{price:3},{price:2},{price:1}]
// 其他排序 https://sort.hust.cc/2.selectionsort#3.-javascript-dai-ma-shi-xian

数组最大值

1
2
3
4
5
6
7
Math.max(...[1, 2, 3, 4]) 
// 4
Math.max.apply(this, [1, 2, 3, 4])
// 4
[1, 2, 3, 4].reduce( (prev, cur,curIndex,arr)=> {
return Math.max(prev,cur);
},0) // 4

类数组转数组

1
2
Array.from({ 0: 'aaa', '1': 'bbb', '二': 'ccc', 4: 'eee', length: 6 })
// ['aaa', 'bbb', undefined, undefined, 'eee', undefined]

数组转对象

1
2
3
4
5
6
{ ...['aaa', 'bbbb', 'cccc', 'dddd'] }
// {0: 'aaa', 1: 'bbbb', 2: 'cccc', 3: 'dddd'}
Object.keys({name:'张三',age:14}) // ['name','age']
Object.values({name:'张三',age:14}) // ['张三',14]
Object.entries({name:'张三',age:14}) // [[name,'张三'],[age,14]]
Object.fromEntries([name,'张三'],[age,14]) // ES10的api,Chrome不支持, firebox输出{name:'张三',age:14}

__END__