arrays - Who can help to explain this JavaScript algorithm [].filter.call() -
i have task receive unique element in order string parameter. not understand how function uniqueelements returns ['a','b','c','b']
.
var word = "aaaabbbbccbb"; var uniqueelements = function(word) { return [].filter.call(word, (function(elem,index) { return word[index-1] !== elem })); } uniqueelements(word); //it should return ['a','b','c','b']
i checked , read following sources:
mdn mozilla , js blog without success.
it's performing explicit call()
on filter method on array object can pass in string. they're using []
instead of array
because it's shorter syntax or trying clever when wrote it.
normally, filter()
method affect array's own contents. however, call()
-ing it, can change context passing in array, or in case, string (which treated array of characters). runs supplied function each element, keeping element if return value of function true
.
Comments
Post a Comment