本文介绍了检查数组是否是另一个数组的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个数组,

var PlayerOne = ['B', 'C', 'A', 'D'];
var PlayerTwo = ['D', 'C'];

使用javascript检查arrayTwo是否为arrayOne的子集的最佳方法是什么?

What is the best way to check if arrayTwo is subset of arrayOne using javascript?

原因:我试图理清游戏Tic tac toe的基本逻辑,并陷入中间。无论如何,这是我的代码...谢谢堆!

The reason: I was trying to sort out the basic logic for a game Tic tac toe, and got stuck in the middle. Here's my code anyway... Thanks heaps!

var TicTacToe = {


  PlayerOne: ['D','A', 'B', 'C'],
  PlayerTwo: [],

  WinOptions: {
      WinOne: ['A', 'B', 'C'],
      WinTwo: ['A', 'D', 'G'],
      WinThree: ['G', 'H', 'I'],
      WinFour: ['C', 'F', 'I'],
      WinFive: ['B', 'E', 'H'],
      WinSix: ['D', 'E', 'F'],
      WinSeven: ['A', 'E', 'I'],
      WinEight: ['C', 'E', 'G']
  },

  WinTicTacToe: function(){

    var WinOptions = this.WinOptions;
    var PlayerOne = this.PlayerOne;
    var PlayerTwo = this.PlayerTwo;
    var Win = [];

    for (var key in WinOptions) {
      var EachWinOptions = WinOptions[key];

        for (var i = 0; i < EachWinOptions.length; i++) {
          if (PlayerOne.includes(EachWinOptions[i])) {
            (got stuck here...)
          }

        }
        // if (PlayerOne.length < WinOptions[key]) {
        //   return false;
        // }
        // if (PlayerTwo.length < WinOptions[key]) {
        //   return false;
        // }
        //
        // if (PlayerOne === WinOptions[key].sort().join()) {
        //   console.log("PlayerOne has Won!");
        // }
        // if (PlayerTwo === WinOptions[key].sort().join()) {
        //   console.log("PlayerTwo has Won!");
        // } (tried this method but it turned out to be the wrong logic.)
    }
  },


};
TicTacToe.WinTicTacToe();


推荐答案

正确的解决方案是:

ES6 语法中:

PlayerTwo.every(val => PlayerOne.includes(val));

ES5 语法:

PlayerTwo.every(function(val) { return PlayerOne.indexOf(val) >= 0; });

这篇关于检查数组是否是另一个数组的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:36