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

前端 未结 7 1101
情深已故
情深已故 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:19

    If you don't understand what a code do, you can log actions ! IE

    var word = "AAAABBBBCCBB";
    function uniqueElements(word){
        return [].filter.call(word,(
            function(elem,index) { 
            console.log("Index : "+index+" | Elem : " +elem+" | CompareTo "+word[index-1]);
                return word[index-1] !== elem;
            }
        ));
    }
    uniqueElements(word); 
    

    You will get the following input :

    Index : 0 | Elem : A | CompareTo undefined
    Index : 1 | Elem : A | CompareTo A
    Index : 2 | Elem : A | CompareTo A
    Index : 3 | Elem : A | CompareTo A
    Index : 4 | Elem : B | CompareTo A
    Index : 5 | Elem : B | CompareTo B
    Index : 6 | Elem : B | CompareTo B
    Index : 7 | Elem : B | CompareTo B
    Index : 8 | Elem : C | CompareTo B
    Index : 9 | Elem : C | CompareTo C
    Index : 10 | Elem : B | CompareTo C
    Index : 11 | Elem : B | CompareTo B
    

    Using this, you can check that every element who aren't equal than the one before are send to your array.

    Few answers/comments already pointed out how [].filter.call() work.

    If you want to get a String instead of an array, simply add .join("") IE

    var word = "AAAABBBBCCBB";
    function uniqueElements(word){
        return [].filter.call(word,(
            function(elem,index) { 
            console.log("Index : "+index+" | Elem : " +elem+" | CompareTo "+word[index-1]);
                return word[index-1] !== elem;
            }
        )).join("");
    }
    uniqueElements(word); 
    

提交回复
热议问题