Description:

Given few numbers, you need to print out the digits that are not being used.

Example:

unusedDigits(12, 34, 56, 78) // "09"
unusedDigits(2015, 8, 26) // "3479"

Note:

Result string should be sorted
The test case won't pass Integer with leading zero

我最初的解法:

function unusedDigits() {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var arguArray = arguments;
    var s = "";
    for (var i = 0; i < arguArray.length; i++) {
        var lalla = arguArray[i].toString();
        s += lalla;
    }
    for (var j = 0; j < s.length; j++) {
        for (var k = 0; k < arr.length; k++) {
            if (s.charAt(j) == arr[k].toString()) {
                arr.splice(k, 1);
            }
        }
    }
    return arr.join("");
}
unusedDigits(12, 34, 56, 78);

然后发现数组转字符串没有这么麻烦,用join("")就可以搞定,于是优化了一下变成

function unusedDigits() {
    var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    var s=[].join.call(arguments,"");
    for (var j = 0; j < s.length; j++) {
        for (var k = 0; k < arr.length; k++) {
            if (s.charAt(j) == arr[k].toString()) {
                arr.splice(k, 1);
            }
        }
    }
    return arr.join("");
}
unusedDigits(12, 34, 56, 78);

然后我在其他人的解法里看到有好多map, forEach, filter, reduce等函数,之前一直也没好好整理一下,现在借此机会整理一下,方便以后回顾。
知乎上这篇写的很好:https://www.zhihu.com/question/24927450
大概能概括这几个函数了

大牛的解法:

function unusedDigits(...args){ return "0123456789".replace(new RegExp('['+args.join('')+']','g'), '')}

比较实际的写法:

function unusedDigits() {
    return [].reduce.call(arguments, function (left, num) {
        (num + '').split('').map(function (digit) {
            left = left.replace(digit, '');
        });
        return left;
    }, '0123456789');
}

雯子
801 声望19 粉丝

life is always like this