这是如何更好地利用JavaScript数组的方法
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/
相关文章:

07、C语言——函数
函数 1、函数定义 函数返回值类型 函数名(形式参数列表) { 函数体; } 注意: 定义有参函数时,形参的定义可以采用传统方式或现代方式两种 1)传统方式: int …

This is probably not a problem with npm. There is likely additional logging output above
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 E:\weii_objct\invoice-manage-web-view>npm start > ant-design-pro@2.1.0 start E:\weii_objct\invoice-manage-web-view > cross-env APP_TYPE=site umi dev cross-env 不是内部或外部命令…

parcel react_如何使用Parcel捆绑React.js应用程序
parcel reactby Michael Ozoemena迈克尔奥索埃梅纳(Michael Ozoemena) 如何使用Parcel捆绑React.js应用程序 (How to use Parcel to bundle your React.js application) 什么是包裹? (What’s Parcel?) Parcel is a web application bundler which offers a blazi…

SparkSQL 与 Spark Core的关系
不多说,直接上干货! SparkSQL 与 Spark Core的关系 Spark SQL构建在Spark Core之上,专门用来处理结构化数据(不仅仅是SQL)。 Spark SQL在Spark Core的基础上针对结构化数据处理进行很多优化和改进, 简单来讲: Spark SQ…

linux操作系统-设置静态ip
在使用linux虚拟机的时候因为经常有关机的需求,然后重新开机后可能面临这上一次获取的ip被改变,在这里我分享一下在linux 下设置静态ip的经验 1.查看路由状态 [rootlocalhost ~]# route -n Kernel IP routing table Destination Gateway Genmask Flags Met…

判断数组里面的下标是否等于一个字符串
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 使用includes() 1、判断字符串里面是否包含一个字符串 示例: var a aaaaaaaavconsole.log(a.includes(v)); //truevar a aaaaaaaavconsole.log(a.includes(c)); //falsevar a aa…

如何获得更多的自由开发者客户
by Jad Joubran通过贾德乔布兰(Jad Joubran) 如何获得更多的自由开发者客户 (How to get more clients as a freelance developer) 我希望几年前知道的实用技巧 (Practical tips I wish I knew a few years ago) Whenever a conversation about freelancing kicks off with fe…

2017.6.4 入门组 NO.2——睡眠
其实这题就是将第二个时间-第一个时间,小于0的补全就A了代码如下: var x,y,k:string;l1,l2,x1,x2,x3,y1,y2,y3:longint; beginreadln(x);readln(y);l1:pos(:,x);l2:pos(:,y);k:copy(x,1,2); val(k,x1);k:copy(x,l11,2); val(k,y1);k:copy(y,1,2); val(k…

微信小程序获取用户收货地址 完整代码
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 获取用户收货地址需要用户点击授权,所以有两种情况,确认授权、取消授权。 情况一,用户第一次访问用户地址授权,并且点击确定授权。 情况二,用…

easyui的combobox下拉框初始化默认值以及保持该值一直显示的方法
easyui的combobox下拉框默认初始值是空,下面是实现从远程加载数据之后初始化默认值,以及让该值一直排在下拉框的最顶部的方式。 目前的需求是需要在初始化的时候添加"全部数据库"字段,并且在下拉的时候,"全部数据库"一直排在最顶部。 初始化效果…

关系数据库非关系数据库_如何与关系数据库最佳配合
关系数据库非关系数据库Relational databases handle data smoothly, whether working with small volumes or processing millions of rows. We will be looking at how we can use relational databases according to our needs, and get the most out of them.关系数据库无论…

看过的bootstrap书籍(附下载地址)
http://yun.baidu.com/share/link?shareid3820784617&uk1008683945 以下书籍下载地址。 《BootStrap入门教程》 就是网上的常规教程,过了一遍,不是很重要。 《Bootstrap实战_第一章》 没找到其余的章节,不过这本书不如直接看网上的boots…

Sql的连接表补充
连接条件可在FROM或WHERE子句中指定,建议在FROM子句中指定连接条件。WHERE和HAVING子句也可以包含搜索条件,以进一步筛选连接条件所选的行。 连接可分为以下几类: 内连接。(典型的连接运算,使用像 或 <…

js正则验证身份证号是否正确
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 封装js公共方法 //验证身份证格式 const IdentityCodeValid sId > {const aCity { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古…

jupyter笔记本_如何为Jupyter笔记本电脑设置PySpark
jupyter笔记本by Tirthajyoti Sarkar由Tirthajyoti Sarkar 如何为Jupyter笔记本电脑设置PySpark (How to set up PySpark for your Jupyter notebook) Apache Spark is one of the hottest frameworks in data science. It realizes the potential of bringing together both …

php 判断是否有相同的ID,如果有就修改数据库字段,没有就插入数据库字段
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 php代码 <?phpheader("Content-Type:text/html;charsetutf8"); header("Access-Control-Allow-Origin: *"); //解决跨域header(Access-Control-Allow-Methods:POST);// 响应类…

MySql存储引擎特性对比
下表显示了各种存储引擎的特性: 其中最常见的两种存储引擎是MyISAM和InnoDB 刚接触MySQL的时候可能会有些惊讶,竟然有不支持事务的存储引擎,学过关系型数据库理论的人都知道,事务是关系型数据库的核心。但是在现实应用中ÿ…

如何使用React提前三天计划
by Mohit Jain由Mohit Jain 如何使用React提前三天计划 (How you can plan three days ahead with React) Today we’ll be making a ‘to-do’ website… with some different features.今天,我们将建立一个具有一些不同功能的“待办事项”网站。 You can check …

ajax 基础
ajax基础模式 url : "Handler.ashx", -- 提交到哪个服务端 data: { "uname": s }, -- 提交的数据,以键值对的方式传字符串,只能是字符串,可以传多个。 type: "post", …

wamp配置虚拟域名
1、打开apache下httpd.conf 我的目录是在F:\wamp\bin\apache\apache2.2.22\conf\httpd.conf 2、去掉这两行前面的#注释 LoadModule rewrite_module modules/mod_rewrite.so Include conf/extra/httpd-vhosts.conf 这两个注释 3、配置httpd-vhosts.conf <VirtualHost *:80>…

VUE 事件获取当前组件的属性
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 for循环把当前的item传递给绑定事件: <block v-for"(item, index) in data_list"><div v-on:clickchangeType(item) class"ci "><div class"cib&q…

javascript计时器_JavaScript计时器:您需要了解的一切
javascript计时器by Samer Buna通过Samer Buna JavaScript计时器:您需要了解的一切 (JavaScript Timers: Everything you need to know) A few weeks ago, I tweeted this interview question:几周前,我在推特上发布了这个面试问题: *** An…
软考总结——虚存管理
存储管理是操作系统的重要职能之中的一个,主要任务是对内存空间进行分配与回收。因为计算机内存容量有限(如今一般都是32位或64位系统),而外存储设备的容量增长速度很快,比如移动硬盘已经到了…

微信小程序与H5相互跳转和传递数据
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 这是小程序和web-vew的H5相互传参,H5使用小程序的微信支付的代码 H5部分 <!DOCTYPE html> <html><head><meta charset"utf-8" /><!--<meta name&…

【算法】弗洛伊德(Floyd)算法
这个算法主要要弄懂三个循环的顺序关系。 弗洛伊德(Floyd)算法过程:1、用D[v][w]记录每一对顶点的最短距离。2、依次扫描每一个点,并以其为基点再遍历所有每一对顶点D[][]的值,看看是否可用过该…

二次开发photoshop_Photoshop 101:Web开发人员简介
二次开发photoshop介绍 (Introduction) Often, when working as web developer, we need to integrate templates. They can be from Photoshop or other software. In this article, we will have a look at the basics of Photoshop for web developers.通常,在作…

html 提交表单,图片和文字一起提交,图片存入服务器,图片地址和表单信息存入数据库,带后端php代码
微信小程序开发交流qq群 173683895 承接微信小程序开发。扫码加微信。 html <!DOCTYPE html> <html><head><meta name"viewport" content"widthdevice-width, initial-scale1.0, user-scalableno, minimum-scale1.0, maximum-scale1.0…

mysql-理想的索引
1.查询频繁 2.区分度高 例如:数据库表字段:sex 存储:男女,区分度就不高。 3.长度小 索引的长度直接影响索引文件的大小,影响增删改的速度,并间接影响查询速度。 4.尽可能覆盖常用字段 转载于:https://www.c…

使用java的Calendar对象获得当前日期的上几个度开始、结束时间
思路: 先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期 /*** param flag true:开始日期;false:结束日期* return*/public static String getLastQuarterTime(boolean flag){…

快速 开发平台 架构_快速介绍清洁架构
快速 开发平台 架构by Daniel Deutsch由Daniel Deutsch 快速介绍清洁架构 (A quick introduction to clean architecture) In an open source project I started to contribute to, the concept of “clean architecture” was brought to me.在一个我开始参与的开源项目中 &a…