javascript - 使用 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;
}
但结果不是很一致,有时只能工作。
解决方案
很难说出你的期望:
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));
推荐阅读
- node.js - 如何在Sinon中使用多个参数存根猫鼬方法?
- vb.net - 初始化字体的最佳事件
- python - 如何使用 QWebEngine 在同一窗口中打开任何链接(_blank)
- kubernetes - 在 Kubernetes 中校准应用程序
- c# - 如何使用 sqlite 数据库上传和检索图像
- android - 安全异常:尝试通过 appium 检查器打开 Facebook 应用程序时拒绝权限
- c# - 如何 C# 调整图片大小 Docx
- twitter - 在 .NET Core 2.2 中处理 Twitter API 以验证访问令牌
- python - 修改列表中的字符串 - 在特定索引处
- capl - 如何在 Capl 测试模块中使用 capl 发送循环罐消息