Who can help to explain this JavaScript algorithm [].filter.call()

前端 未结 7 996
情深已故
情深已故 2021-01-22 03:41

I have task to receive unique element in order from string as parameter. I do not understand how this function uniqueElements returns [\'A\',\'B\',\'C\',\'B\']

7条回答
  •  无人及你
    2021-01-22 04:21

    var uniqueElements = function(word) {
        return [].filter.call(word, (function(elem,index) {
            return word[index-1] !== elem
        }));
    }    
    

    is equivalent to

    var uniqueElements = function(word) {
        return word.split("").filter(function(elem,index) {
            return word[index-1] !== elem
        });
    }    
    

    which should already be clearer: it turns word into an array of char then filters every char that is different from the previous one. This explains why "B" is present twice in the result.

    To get unique elements, you can do

    var uniqueElements = function(word) {
        var res = []
        word.split("").forEach(function(val){
            if (res.indexOf(val)===-1) res.push(val);
        });
        return res
    }  
    

提交回复
热议问题