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

时间:2015-01-04 03:43:05

标签: javascript arrays contains

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

这曾经是我的代码:

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;
};

我正在寻找arr1的任何元素,它是arr2或arr3的一部分,例如:

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')

1 个答案:

答案 0 :(得分:0)

好的,我想我解决了它:

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中每个元素的格式(一个字符串,这可能很容易转换为数组)。

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