如何检查数组是否包含不同顺序的字符串?

How to check if an array contains a string in a different order?

基本上我想做的是在我的数组中搜索一个字符串

这曾经是我的代码:

var arr1 = ['23456', '34567', '45678', '56789', '6789T', '789TJ', '89TJQ', '9TJQK', 'TJQKA'];
var arr2 = ['98TJQ'];
var arr3 = ['89TJQ'];

if (!('containsU' in Array.prototype))
    Array.prototype.containsU = function(arr, startIndex) {
        for (i in arr) {
            if (arr.hasOwnProperty(i) && ''.indexOf.call(this, arr[i], startIndex) === -1) return false;
        }
        return true;
    };
if (!('containsArrayU' in Array.prototype)) //contains array unordered
    Array.prototype.containsArrayU = function(arr, startIndex) {
    for (i in this) {
        if (this.hasOwnProperty(i) && arr.containsU(this[i])) return true;
    }
    return false;
};

我正在寻找属于 arr2 或 arr3 的 arr1 的任何元素,例如:

arr1 = ['222','333','444','555','666','777','888','999','TTT','JJJ','QQQ','KKK','AAA'];
arr2 = ['9229'];
arr3 = ['9299'];
alert(arr2.containsArrayU(arr1)); //this should be false
alert(arr3.containsArrayU(arr1)); //this should be true (contains '999')

好的,我想我解决了:

var arr1 = ['23456','34567','45678','56789','6789T','789TJ','89TJQ','9TJQK','TJQKA'];
var arr2 = '98TJQ';
var arr3 = '89TJQ';

if (!('removeAt' in String.prototype))
    String.prototype.removeAt = function(index) { return this.slice(0, index) + this.slice(index+1); };
if (!('containsU' in String.prototype)) //string contains each element of another string
    String.prototype.containsU = function(str, startIndex) {
        var newString = this;
        for(i in str) { 
            if(str.hasOwnProperty(i)) {
                var index = newString.indexOf(str[i]);
                if (index===-1) return false;
                newString = newString.removeAt(index);
            }
        } return true;
    }
if (!('containsArrayU' in String.prototype))  //contains some element in array
    String.prototype.containsArrayU = function(arr, startIndex) { 
        for(i in arr) { if(arr.hasOwnProperty(i) && this.containsU(arr[i])) return true; } return false; };

alert(arr2.containsArrayU(arr1));
alert(arr3.containsArrayU(arr1));

arr1 = ['222','333','444','555','666','777','888','999','TTT','JJJ','QQQ','KKK','AAA'];
arr2 = '9229';
arr3 = '92422';
alert('9299'.containsU('999'));
alert(arr2.containsArrayU(arr1)); //this should be false
alert(arr3.containsArrayU(arr1)); //this should be true

jsfiddle.net

我所做的只是将 arr2 和 arr3 更改为 arr1 中每个元素的格式(一个字符串,这可能很容易转换为数组)。

为了在字符串中查找重复的数字,我创建了一个临时数字并删除了已经搜索过的字符。