簡體   English   中英

如何使用 .some() 檢查數組中是否存在元素?

[英]How do I check if elements exist in an array using .some()?

我正在嘗試查看數組中是否存在一對特定的數字。 我知道 .some() 在它是一個簡單數組時可以有效地工作,但我似乎無法讓它在嵌套數組中工作。

先感謝您。

 const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; // checks whether an element exists const exists = (i) => i == [3, 1] || [1, 3]; console.log(array.some(exists)); // expected output: true

由於不同的數組,您有不同的對象引用,並且您誤用了邏輯OR運算符,因此您需要檢查每個值。 這不包括與另一個值的比較。

 const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; const exists = ([a, b]) => a === 3 && b === 1 || a === 1 && b === 3; console.log(array.some(exists));

這是一個通用的解決方案。

const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]];
const expected = [[1, 3], [3, 1]];
const exists = (i) => expected.some((j) => {
    return i.every((k, n) => j[n] === k);
});

console.log(array.some(exists));

這可以包裝在一個函數中以使其可重用。

const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]];
const expected = [[1, 3], [3, 1]];

const containsAny = (array, expected) => {
  return array.some((i) => expected.some((j) => {
    return i.every((k, n) => j[n] === k);
  }))
};


console.log(containsAny(array, expected));

您可以使用它制作自定義功能,使其可重用。 這是一個簡單的例子。 通過展平數組,您可以檢查值是否相同。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some上得到我的靈感

 const array = [[1, 0], [2, 0], [3, 1], [4, 3], [5, 2]]; const checkArrayFor = (needle, haystack) => { const flattenNeedle = needle.join(':'); const flattenArray = haystack.map(item => item.join(':')); return flattenArray.includes(flattenNeedle); }; console.log("Check for [1, 0]", checkArrayFor([1, 0], array)); console.log("Check for [1, 1]", checkArrayFor([1, 1], array));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM