简体   繁体   English

检查阵列存在和状况的最快/最短方法

[英]Quickest/Shortest way to check array existence and condition

I feel this is a really simple question but as a beginner I cannot find the answer. 我觉得这是一个非常简单的问题,但是作为初学者,我找不到答案。

Ultimately I want to check an element exists in an array ( eg userProfile.friendRequests ). 最终,我想检查数组中是否存在某个元素( 例如, userProfile.friendRequests )。

I end up using includes as a simple check ie 我最终使用includes作为一个简单的检查

checkRequest(friendReqUid) {
  return userProfile.friendRequests.includes(friendReqUid)
}

However sometimes that array might not even exist and the only way that I can see to check the condition is to add a check for the entire array beforehand ie 但是有时该数组可能甚至不存在,而我可以看到的检查条件的唯一方法是事先对整个数组进行检查,

 checkRequest(friendReq) {
   return userProfile.friendRequest && userProfile.friendRequest.includes(friendReq)
 }

If I do this within the template (to show a button, etc.) this ends up being really long winded way to do this. 如果我在模板中执行此操作(以显示按钮等),则最终会导致执行此操作的时间很长。

Is there a quicker function/way to check that an array exists and if an element is present or not, instead of adding another check for the presence of the actual array? 有没有一种更快的功能/方法来检查数组是否存在以及是否存在元素,而不是添加另一个检查是否存在实际数组的方法?

Thanks 谢谢

The shortest way to do it that I know of is to default to an empty array if the property is falsy: 我知道,最短的方法是如果属性为falsy,则默认为空数组:

(userProfile.friendRequests || []).includes(friendReqUid)

But I usually check if the object exists before accessing the array, so it is more robust: 但是我通常在访问数组之前检查对象是否存在,因此它更可靠:

(userProfile && userProfile.friendRequests || []).includes(friendReqUid)

EDIT : If you want to do the same for push() , you can do this: 编辑 :如果要对push()执行相同操作,则可以执行以下操作:

userProfile && (userProfile.friendRequests = userProfile.friendRequests || []).push(friendReqUid)

This will initialize the array to [] if it is falsy. 如果是假的,这会将数组初始化为[]

However, you might consider splitting this on separate lines so it is more readable. 但是,您可以考虑将其拆分为单独的行,以便于阅读。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM