by pacdiv

由pacdiv

这是如何更好地利用JavaScript数组的方法 (Here’s how you can make better use of JavaScript arrays)

Quick read, I promise. Over the last few months, I noticed that the exact same four mistakes kept coming back through the pull requests I checked. I’m also posting this article because I’ve made all these mistakes myself! Let’s browse them to make sure we correctly use Array methods!

我保证,请快速阅读。 在过去的几个月中,我注意到在我检查的拉取请求中,又出现了同样的四个错误。 我也发布了这篇文章,因为我自己犯了所有这些错误! 让我们浏览它们以确保我们正确使用Array方法!

用Array.includes替换Array.indexOf (Replacing Array.indexOf with Array.includes)

“If you’re looking for something in your Array, use Array.indexOf.” I remember reading a sentence like this one in my course when I was learning JavaScript. The sentence is quite true, no doubt!

“如果要在数组中查找内容,请使用Array.indexOf。” 我记得在学习JavaScript的过程中读过这样的句子。 毫无疑问,这句话是真的!

Array.indexOf “returns the first index at which a given element can be found,” says the MDN documentation. So, if we use the returned index later in our code, and Array.indexOf is the solution.

MDN文档说:Array.indexOf“返回可以找到给定元素的第一个索引”。 因此,如果我们稍后在代码中使用返回的索引,则Array.indexOf是解决方案。

But, what if we only need to know if our array contains a value or not? Seems like a yes/no question, a boolean question I would say. For this case, I recommend using Array.includes which returns a boolean.

但是,如果我们只需要知道数组是否包含值怎么办? 好像是/否的问题,我会说一个布尔问题。 对于这种情况,我建议使用Array.includes返回一个布尔值。

使用Array.find代替Array.filter (Using Array.find instead of Array.filter)

Array.filter is a very helpful method. It creates a new array from another one with all items passing the callback argument. As indicated by its name, we must use this method for filtering, and for getting a shorter array.

Array.filter是一个非常有用的方法。 它从另一个数组创建一个新数组,所有项目都传递回调参数。 顾名思义,我们必须使用此方法进行过滤并获得较短的数组。

But, if we know our callback function can return only one item, I would not recommend it — for example, when using a callback argument filtering through a unique ID. In this case, Array.filter would return a new array containing only one item. By looking for a specific ID, our intention may be to use the only value contained in the array, making this array useless.

但是,如果我们知道回调函数只能返回一项,那么我不建议您使用它,例如,当使用通过唯一ID进行过滤的回调参数时。 在这种情况下,Array.filter将返回一个仅包含一项的新数组。 通过查找特定的ID,我们的意图可能是使用数组中包含的唯一值,从而使该数组无用。

Let’s talk about the performance. To return all items matching the callback function, Array.filter must browse the entire array. Furthermore, let’s imagine that we have hundreds of items satisfying our callback argument. Our filtered array would be pretty big.

让我们谈谈性能。 若要返回所有与回调函数匹配的项目,Array.filter必须浏览整个数组。 此外,让我们想象一下,有数百个满足回调参数的项。 我们过滤后的数组会很大。

To avoid these situations, I recommend Array.find. It requires a callback argument like Array.filter, and it returns the value of the first element satisfying this callback. Furthermore, Array.find stops as soon as an item satisfies the callback. There is no need to browse the entire array. Also, by using Array.find to find an item, we give a clearer idea about our intention.

为了避免这些情况,我建议使用Array.find。 它需要像Array.filter这样的回调参数,并返回满足此回调的第一个元素的值。 此外,只要项满足回调,Array.find就会停止。 无需浏览整个阵列。 另外,通过使用Array.find查找项目,我们可以更清楚地了解我们的意图。

用Array.some替换Array.find (Replacing Array.find with Array.some)

I admit I’ve made this mistake many times. Then, a kind friend told me to check the MDN documentation for a better way. Here’s the thing: this is very similar to our Array.indexOf/Array.includes case above.

我承认我犯了很多错误。 然后,一个好心的朋友告诉我检查MDN文档以寻求更好的方法。 事情是这样:这与我们上面的Array.indexOf / Array.includes情况非常相似。

In the previous case, we saw Array.find requires a callback as an argument and returns an element. Is Array.find the best solution if we need to know whether our array contains a value or not? Probably not, because it returns a value, not a boolean.

在前一种情况下,我们看到Array.find需要将回调作为参数并返回一个元素。 如果我们需要知道数组是否包含值,Array.find是否是最佳解决方案? 可能不是,因为它返回一个值,而不是布尔值。

For this case, I recommend using Array.some which returns the needed boolean. Also, semantically, using Array.some highlights the fact that we don’t need the found item.

对于这种情况,我建议使用Array.some返回所需的布尔值。 同样,从语义上讲,使用Array.some可以突出表明我们不需要找到的项目。

使用Array.reduce而不是链接Array.filter和Array.map (Using Array.reduce instead of chaining Array.filter and Array.map)

Let’s face it, Array.reduce isn’t simple to understand. It’s true! But, if we run Array.filter, then Array.map it feels like we’re missing something, right?

面对现实,Array.reduce并不容易理解。 这是真的! 但是,如果我们运行Array.filter,那么Array.map就像我们缺少了什么,对吗?

I mean, we browse the array twice here. The first time to filter and create a shorter array, the second time to create a new array (again!) containing new values based on the ones we obtained from Array.filter. To get our new array, we used two Array methods. Each method has its own callback function and an array that we cannot use later — the one created by Array.filter.

我的意思是,我们在这里浏览了两次数组。 第一次过滤并创建一个较短的数组,第二次创建一个新数组(再次!),该数组包含基于从Array.filter获得的值的新值。 为了获得新的数组,我们使用了两个Array方法。 每个方法都有其自己的回调函数和一个以后不能使用的数组-由Array.filter创建的数组。

To avoid low performances on this subject, my advice is to use Array.reduce instead. Same result, better code! Array.reduce allows us to filter and add the satisfying items into an accumulator. As an example, this accumulator can be a number to increment, an object to fill, a string or an array to concat.

为了避免在此主题上表现不佳,我的建议是改用Array.reduce。 结果相同,代码更好! Array.reduce允许我们过滤令人满意的项目并将其添加到累加器中。 例如,此累加器可以是要递增的数字,要填充的对象,字符串或要连接的数组。

In our case, since we’ve been using Array.map, I recommend using Array.reduce with an array to concat as an accumulator. In the following example, depending on the value of env, we will add it into our accumulator or leave this accumulator as is.

在我们的例子中,由于我们一直在使用Array.map,因此我建议将Array.reduce与一个数组结合起来用作累加器。 在下面的示例中,根据env的值,我们将其添加到累加器中或将该累加器保持原样。

而已! (That’s it!)

Hope this helps. Be sure to leave comments if you have any thoughts on this article or have any other use cases to show. And if you found it helpful, give me some claps ? and share it. Thanks for reading!

希望这可以帮助。 如果您对本文有任何想法或需要展示的其他用例,请务必发表评论。 如果您觉得有帮助,请给我一些鼓掌吗? 并分享。 谢谢阅读!

PS: You can follow me on Twitter here.

PS:您可以在Twitter上关注我 。

Note: As mentioned by malgosiastp and David Piepgrass in the comments, please check the support before using Array.find and Array.includes, which are currently not supported by Internet Explorer.

注意:如malgosiastp和David Piepgrass在评论中所述,请在使用Array.find和Array.includes之前检查支持,这些是Internet Explorer目前不支持的。

翻译自: https://www.freecodecamp.org/news/heres-how-you-can-make-better-use-of-javascript-arrays-3efd6395af3c/

这是如何更好地利用JavaScript数组的方法相关推荐

  1. 如何更好地利用JavaScript数组

    用Array.includes替换Array.indexOf Array.indexOf"返回可以找到给定元素的第一个索引,"MDN文档说.但是,如果我们只需要知道我们的数组是否包 ...

  2. 判断javascript数组的方法

    2019独角兽企业重金招聘Python工程师标准>>> 判断javascript数组的方法 var is_array=function(){ return value &&a ...

  3. 利用非数组的方法输出杨辉三角

    大家知道利用数组数组的方法输出杨辉三角是一件比较容易的事情,在许多的教材上都能够找到,而且计算速度比较快,但是有个缺点就是当输出的阶数比较大的时候,需要占用较多的存储空间. 下面我尝试用利用非数组的方 ...

  4. JavaScript数组归并方法reduce

    示例代码: <!DOCTYPE html> <html lang="zh"><head><meta charset="UTF-8 ...

  5. JavaScript 数组遍历方法的对比

    前言 JavaScript 发展至今已经发展出多种数组的循环遍历的方法,不同的遍历方法运行起来那个比较快,不同循环方法使用在那些场景,下面将进行比较: 各种数组遍历的方法 for 语句 代码: var ...

  6. splice方法_[7000字]JavaScript数组所有方法基础总结

    基础决定一个人的上限,很多时候我们感叹别人在实现一个功能时使用方法的精妙,并且反思,为什么别人想的出来自己却想不出来?我觉得主要是因为对于基础的掌握上有很大的差距.本文总结数组的所有方法的基础使用,希 ...

  7. JavaScript数组sort()方法小结

    sort语法:arrayObject.sort(sortby):参数sortby可选.规定排序顺序.必须是函数. 由于sort方法是先将数组元素转换为字符串进行比较,根据字符串首字符的ASCII码排序 ...

  8. JavaScript 数组filter方法完整介绍

    数组过滤器方法是 JavaScript 中使用最广泛的方法之一. 它允许我们快速过滤出具有特定条件的数组中的元素. 因此,在本文中,您将了解有关过滤器方法及其各种用例的所有内容. 所以让我们开始吧. ...

  9. JavaScript 数组去重方法合集(简洁易懂)

    JavaScript数组去重 JavaScript去重的七种方法 简单易懂 方法一:暴力去重法 // 暴力去重法 function ArrayIsUnique (array) {if (!Array. ...

最新文章

  1. android aidl接口初步了解
  2. libevent源码深度剖析八
  3. Ubuntu中的vi模式中的按上下左右键变成ABCD解决方法
  4. scala 样例类(case class) + 模式匹配代码示例
  5. 好久不碰Blog,最近要二次毕业了,继续写点警醒自己的话
  6. 前端面试题集锦(一)之HTML部分
  7. 单链表删除所有值为x的元素_线性表之单链表
  8. 给Domino系统管理员的十二项建议
  9. C# WPF MVVM开发框架Caliburn.Micro 名称Transformer⑩①
  10. 搭建java_搭建JAVA环境
  11. 在VS2013平台下如何快速解决c++代码内存泄漏问题
  12. PC-用Windows XP自带的组策略加固操作系统
  13. mbstring未安装
  14. laravel-echo-server 不接收失败_6所高校公布报名不合格名单!这些问题最容易出错...
  15. 谷歌升级云数据库:更多的储存及更快的读取
  16. Android原生PDF功能实现,掌握了这些Android高级工程师必备知识,
  17. 江苏事业单位计算机类考试题型,江苏事业单位统考各岗位考试类型和题目分值一览!...
  18. 戴尔计算机没有硬盘驱动,在Dell计算机上重新安装系统后,如果找不到硬盘驱动器或引导设备该怎么办?...
  19. excel筛选排序从小到大_(Excel)常用函数公式及操作技巧之三:排名及排序筛选(一)...
  20. 计算机管理添加信任,iPhone怎么设置添加信任?苹果手机对电脑添加信任图文教程...

热门文章

  1. Mysql排序后显示排序序号
  2. lua菜鸟教程_Lua 环境安装
  3. JS实现录音,播放完整代码带示例图
  4. WSS 代码执行的权限提升
  5. X-UA-Compatible
  6. java maven项目使用sonar审核代码
  7. Codeigniter文件上传类型不匹配错误
  8. Brian 的 Perl 问题之万能指南
  9. Sqlite3数据库之第三方库FMDB学习心得
  10. 华为AR28-11路由器配置