您的位置 首页 java

工作面试常备:利用Javascript原生API,给数组去重的3种方法

工作面试常备:利用Javascript原生API,给数组去重的3种方法

面试前端的童鞋,经常会被问到这个问题:怎么为Javascript的数组Array去重呢?

看似很基础很简单的问题,却能根据不同回答判断出面试者的水平高低。

即时不是为了面试,数组去重问题也是工作中经常会用到的。

工作面试常备:利用Javascript原生API,给数组去重的3种方法

最传统的方法就是用递归去重,当然是最笨的,因为随着ES标准(ECMAScript)的升级迭代,越来越多的方法可以供我们使用,但是那种方式才时最好的呢?下边介绍3种方法,仅供你选择参考。

方法1:使用 es5 的 filter


使用Array. prototype .filter()方法,对元素进行过滤:

工作面试常备:利用Javascript原生API,给数组去重的3种方法

filter

方法2:利用es6 的 Map 类型


Map是es6新支持的数据类型,其中方法set、has、get、clear、delete、keys都很不错。

工作面试常备:利用Javascript原生API,给数组去重的3种方法

Map

方法3:利用es6 的 Set 类型


利用Set的特性:即元素只能出现一次,即每个元素都是唯一的,跟Java中是类似的。

PS:下面示例中使用了(…)扩展语句,意思是把数组转换成n个对象的方法。

工作面试常备:利用Javascript原生API,给数组去重的3种方法

Set

总结


我觉得第三种方法最优,也是经常用的,起码在代码上更简洁明了,你觉得呢?如有不足,欢迎指正!谢谢:)

文章来源:智云一二三科技

文章标题:工作面试常备:利用Javascript原生API,给数组去重的3种方法

文章地址:https://www.zhihuclub.com/180487.shtml

关于作者: 智云科技

热门文章

评论已关闭

5条评论

  1. Adverse effects of G6PD deficiency on heart failure If you lose weight more quickly than this, you run the risk of losing lean muscle mass disastrous in bodybuilding terms

  2. Overall, these results demonstrate that tamoxifen has significant effects on hepatic phase II enzyme expression that may have implications for the carcinogenicity and or therapeutic activity of the drug

  3. Although IUI is a safe fertility treatment with impressive success rates, patients need to be aware of the potential risks or side effects of this technique

  4. Cagnacci and colleagues 84 showed that melatonin administration had an enhancing effect on LH and FSH and possibly through GnRH at the follicular, but not the luteal phase, indicating that melatonin s effect on reproductive hormones may vary depending on cycle phase

  5. Placement of nephrostomy catheter, percutaneous, including diagnostic nephrostogram and or ureterogram when performed, imaging guidance eg, ultrasound and or fluoroscopy and all associated radiologic supervision and interpretation

网站地图