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

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

    I've split the code into smaller parts with inline comments for better understanding.

    var word = "AAAABBBBCCBB";
    var uniqueElements = function(word){
        // this is the filter function
        // this function will get each element of the string with its index
        var filterFunction = function(elem, index) {
            // the elements who pass the following condition are kept
            // the condition - 
            // if the character at the previous index (index-1) is not equal to the 
            // current element, then keep the element
            return word[index-1] !== elem;
        }
    
        // the below is equivalent to Array.prototype.filter.call(context, filterFunction)
        return [].filter.call(word, filterFunction);
    }
    console.log(uniqueElements(word));
    

提交回复
热议问题