首页 > 解决方案 > 获取 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()和迭代数组并将结果保存在外部数组中,以便我可以检查长度,类似于:mapfor

const isCoolArr = []
coolArray.map(item => item.isCool ? isCoolArr.push(item) : false)
console.log('expected result:', isCoolArr.length) // outputs 1

但我对这种方法并不特别满意,并在寻找更简单的替代方案。可以满足我.some()的需要还是我需要另一种选择?除了我上面提到的情况之外,还有其他的吗?

标签: javascriptarrays

解决方案


使用.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")
}


推荐阅读