简体   繁体   English

在数组中只有一个元素时使用包含()方法是否有效?

[英]Using includes() method when having only one element in an array is it efficient?

Does the below code blocks vary in performance especially when the array has only one element?以下代码块的性能是否有所不同,尤其是当数组只有一个元素时?

myArray.includes(anElement);

and

myArray.length === 1 && myArray[0] === anElement

Please tell which is a good coding practice and also tell about any performance issues in the above two scenarios.请说出哪种是好的编码习惯,并说明上述两种情况下的任何性能问题。

When the array has only one element - the only difference is the length check.当数组只有一个元素时 - 唯一的区别是长度检查。 So if you are running this in a loop for a long time - probably you will see a difference because of that.因此,如果您长时间循环运行它 - 可能您会因此而看到差异。

But the problem here is that you should not assume that the array has only one element unless you checked it previously, then it's the same.但是这里的问题是你不应该假设数组只有一个元素,除非你之前检查过它,那么它是一样的。

If the array may contain more than one element, then the logic between these two is different and the comparison doesn't make sense.如果数组可能包含多个元素,那么这两者之间的逻辑是不同的,比较没有意义。

Bottom line - to have them with the same logic you will do the same work.底线 - 让它们具有相同的逻辑,你将做同样的工作。 So just make it readable as @Xion 14 suggested.所以就像@Xion 14 建议的那样让它可读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有没有一种方法可以检查数组是否包含 SQLite 中的一个值? - Is there a method to check if an array includes one value in SQLite? Efficient.includes() 在对象数组中搜索 - Efficient .includes() search in array of objects 当数组中只有一个元素时减少对象数组 - Reducing an Array of Objects when there is only one Element in the Array array.includes(element) 仅在 Angular 8(typescript) 中给出 false - array.includes(element) is giving false only in Angular 8(typescript) 如何知道一个字符串是否至少包含 Javascript 中的一个数组元素 - How to know if a string includes at least one element of array in Javascript javascript中仅包含一个元素的表单数组时出现问题 - problems when receiving form array with only one element in javascript 使用npm中的array-includes在数组中查找元素 - Find element in array using array-includes from npm 数组中的每个元素仅应在元素中同时增加 - Every element in an array being incremented simultaneously when only one should be 当字符串中只有一个元素时,如何在jQuery中将字符串拆分为数组? - How to split a string into an array in jQuery when there is only one element in the string? 使用 setState 只更新多维数组的一个元素 - update only one element of multi-dimensional array using setState
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM