[英]Get first element from array or null using Ramda
I have an array我有一个数组
const arr1 = ["string1", "string2"]
const arr2 = []
And I want to get the first element of this array, or null if it is empty.我想获取此数组的第一个元素,如果它为空,则为 null。
How can I do this using Ramda?我怎样才能使用 Ramda 做到这一点?
You can use R.propOr()
to get a value from an object or array by key/index, and return a default if the result is undefined
:您可以使用R.propOr()
通过键/索引从对象或数组中获取值,如果结果undefined
则返回默认值:
const firstOrNull = R.propOr(null, 0) const arr1 = ["string1", "string2"] const arr2 = [] console.log(firstOrNull(arr1)) console.log(firstOrNull(arr2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
I prefer using head
.我更喜欢使用head
。 However, it would return undefined rather than null when the list is empty.但是,当列表为空时,它将返回 undefined 而不是 null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.