javascript - 获取 Array.prototype.some() 的结果长度
问题描述
我有一个条件,通过Array.prototype.some()
. 考虑这个数组:
const coolArray = [
{ isCool: false },
{ isCool: false },
{ isCool: true }
]
const isCool = coolArray.some(item => item.isCool === true)
if (isCool) {
console.log("hello I'm cool!")
}
但是,我希望检查何时发生,item.isCool
并且true
数组中至少有两个项目与条件匹配。所以上面的例子不会输出消息,因为只有一个true
条件。
在MDN上,此方法的参考是arr.some(callback(element[, index[, array]])[, thisArg])
. 但是[, array]
引用原始数组而不是它们的克隆,因此执行以下操作会输出相同的结果:
const isCool = coolArray.some((item, index, arr) => {
return item.isCool === true && arr.length > 1
})
我知道我可以使用or避免.some()
和迭代数组并将结果保存在外部数组中,以便我可以检查长度,类似于:map
for
const isCoolArr = []
coolArray.map(item => item.isCool ? isCoolArr.push(item) : false)
console.log('expected result:', isCoolArr.length) // outputs 1
但我对这种方法并不特别满意,并在寻找更简单的替代方案。可以满足我.some()
的需要还是我需要另一种选择?除了我上面提到的情况之外,还有其他的吗?
解决方案
使用.filter()
,您将失去使用 获得的短路优势.some()
。一种选择是使用回调外部的变量。
const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let count = 0
const isCool = coolArray.some(item => (count += item.isCool) >= 2)
if (isCool) {
console.log("hello I'm cool!")
} else {
console.log("not cool enough")
}
这利用了将布尔值转换为数字的优势。如果你不喜欢这样,你可以更明确。
const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let count = 0
const isCool = coolArray.some(item => item.isCool && ++count >= 2)
if (isCool) {
console.log("hello I'm cool!")
} else {
console.log("not cool enough")
}
或者在不添加额外变量的情况下制作它!
const coolArray = [{isCool: false},{isCool: false},{isCool: true}]
let isCool = 0;
isCool = coolArray.some(item => item.isCool && ++isCool >= 2);
if (isCool) {
console.log("hello I'm cool!")
} else {
console.log("not cool enough")
}
推荐阅读
- java - RecyclerView 没有更新 OnPostExecute() 上的项目
- c++ - 重新定义类成员数据类型
- regex - 美丽的汤发现href不起作用
- vba - 使用VBA从Excel中提取URL而不是在哈希后提取
- cordova - 使用 Ionic Native Push 为 Firebase 云消息传递获取正确的 FCM 注册令牌
- python - 矢量化点积
- javascript - 如何在 ReactJS 中添加嵌套路由 - React Router
- slack-api - Slack API 斜杠命令 - 成功使用 webhook 后返回 502_service_error
- powershell - 复制驱动器中的所有项目并导出到新目标
- reactjs - 使用 MaterialUI Grid 的意外空白空间