欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js小技巧总结

程序员文章站 2023-01-14 20:51:29
js小技巧总结 1、Array.includes条件判断 2、set与去重 ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。Set 本身是一个构造函数,用来生成 Set 数据结构。 数组去重 Array.from 方法可以将 Set 结构转为数组。我们可以专门 ......

js小技巧总结

1、array.includes条件判断

  

1 function test(fruit) {
2   const redfruits = ["apple", "strawberry", "cherry", "cranberries"];
3   if (redfruits.includes(fruit)) {
4     console.log("red");
5   }
6 }

 

2、set与去重

  es6 提供了新的数据结构 set。它类似于数组,但是成员的值都是唯一的,没有重复的值。set 本身是一个构造函数,用来生成 set 数据结构。

  数组去重

  

1 const arr = [3, 5, 2, 2, 5, 5];
2 const unique = [...new set(arr)];
3 // [3,5,2]

  array.from 方法可以将 set 结构转为数组。我们可以专门编写使用一个去重的函数

1 function unique(array) {
2   return array.from(new set(array));
3 }
4 
5 unique([1, 1, 2, 3]); // [1, 2, 3]