首页 > 解决方案 > 使用 every() 检查一个数组是否包含另一个数组的所有元素

问题描述

我有一个每次点击都会改变的数组。每次点击发生时,我都需要找出数组是否包含一组数组上的任何序列。这是给定的一组数组,我将该数组与以下内容进行比较:

const combos = [
      [0, 5, 3],
      [0, 8, 2],
      [0, 0, 1],
      [1, 1, 2],
];

这就是我试图比较它们的方式:

const playerCombo = ( arr ) => {
      //First sort the Array
      const sorted = arr.sort();

      //Initialize the hasWon variable
      let hasWon = '';

      //For each combo Array...
      for( let combo of boardCtrl.combos ){
        if( sorted.length > 2 ) {
          hasWon = combo.every((e)=> sorted.includes(e));
        }
      }

      return hasWon;

    }

但结果不是很一致,有时只能工作。

标签: javascriptarrays

解决方案


很难说出你的期望:

const boardCtrl = {
  combos:[[0, 5, 3], [0, 8, 2], [0, 0, 1], [1, 1, 2]]
}
const testArray = [[0, 0, 1], [0, 8, 2], [1, 1, 2], [0, 5, 3]];
const shouldFail = [[0, 0, 1], [0, 8, 2], [1, 7, 2], [0, 5, 3]];
const playerCombo = array => {
  const bc = boardCtrl.combos;
  let l = bc.length, n = 0;
  if(array.length !== l){
    return false;
  }
  for(let combo of bc){
    for(let a of array){       
      if(a.every(e => combo.includes(e)))n++;
    }
  }
  return n === l;
}
console.log(playerCombo(testArray));
console.log(playerCombo(shouldFail));


推荐阅读