JS数组的几个有逼格操作

JavaScript里的数组提供了很好的api供开发者调用,免去了对很多细节的考虑。可是,这些api在日常开发中常常被忽略,这里总结一下,也算是提醒自己要经常去使用~~

1. 去重

Array.from(new Set([1,2,3,3,4,4]) //[1,2,3,4]
[...new Set([1,2,3,3,4,4])] //[1,2,3,4]

2. 排序

[1,2,3,4 ].sort (); // [1, 2,3,4],默认是升序
[1,2,3,4].sort((a,b) => b - a); // [4,3,2,1] 降序

3. 求和

[1,2,3,4].arr.reduce(function(prev,cur) { 
return prev + cur ; 
}, 0 ) //10

4. 最大值

Math.max(...[1,2,3,4]) //4 

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

5. 合并

[1,2,3,4].concat([5,6]) //[1,2,3,4,5,6]

[...[ 1,2,3,4],...[4,5]] //[1,2,3,4,5,6]

6. 判断是否包含值

[1,2,3].includes(4) //false

[1,2,3].indexOf(4) //-1 如果存在换回索引

[1,2,3].find((item )=> item === 3)) //3 如果数组中无值返回undefined

[1,2,3].findIndex((item)=> item === 3)) //2 如果数组中无值返回-1

7. 每一项是否满足

[1,2,3].every(item =>{ return item > 2}) //false

8. 某一项是否满足

[1,2,3].some(item =>{ return item > 2}) //true

9. 过滤数组

[1,2,3].filter(item =>{ return item > 2 }) //[3]

10. 对象转数组

Object.keys({ name : '张三' , age : 14 }) //['name','age']

Object.values({ name : '张三' , age : 14 }) //['张三',14]

参考

https://mp.weixin.qq.com/s/NSa7_TRt4Ql5Xhif5XETMw

猜你喜欢

转载自blog.csdn.net/colinandroid/article/details/88677088