JS实现的用来对比两个用指定分隔符分割的字符串是否相同

时间:2022-01-24 17:01:53

比较2个字符串内元素的不同(字符1, 字符2, 分隔符可选)

文件: diff.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 示例用法
/*
 
var str1 = "tie, mao, 55";
var str2 = "tie, mao, csdn";
var result = diff(str1, str2, ','); // 对象
var rs = "" + result;  // " 55, csdn"
var df1 = result.diff1; // [" 55"]
var df2 = result.diff2; // [" csdn"]
 
*/
 
// 比较2个字符串内元素的不同(字符1, 字符2, 分隔符可选)
function diff(str1, str2, separator){
    //
    str1 = str1 || "";
    str2 = str2 || "";
    separator = separator || ",";
    // arr中有ele元素
    function hasElement(arr, ele){
        // 内存循环
        var hasItem1 = false;
        for(var i2=0; i2 < arr.length; i2++){
            //
            var item2 = arr[i2] || "";
            if(!item2){
                continue;
            }
            //
            if(ele == item2){
                hasItem1 = true;
                break;
            }
        }
        return hasItem1;
    };
    function inAnotB(a, b){ // 在A中,不在B中
        var res = [];
        for(var i1=0; i1 < a.length; i1++){
            var item1 = a[i1] || "";
            if(!item1){
                continue;
            }
            var hasItem1 = hasElement(b, item1);
            if(!hasItem1){
                res.push(item1);
            }
        }
        return res;
    };
    //
    var list1 = str1.split(",");
    var list2 = str2.split(",");
    //
    var diff1 = inAnotB(list1, list2);
    var diff2 = inAnotB(list2, list1);
    
    // 返回结果
    var result = {
        diff1 : diff1
        ,
        diff2 : diff2
        ,
        separator : separator
        ,
        toString : function(){
            //
            var res = this["diff1"].slice(0);
            res = res.concat(this["diff2"]);
            //
            return res.join(this["separator"]);
        }
    };
    //
    return result;
};

请根据需要使用, 我用来比较在2个Oracle数据库中导出的表有那些没导入成功.