最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - js Array.prototype.filter.call() - can someone explain me how this piece of code works? - Stack Overflow

programmeradmin1浏览0评论

Can someone explain how this piece of code works? The output is a vector with the letters of input but without repetition.

var uniqueInOrder = function (iterable) {
  return [].filter.call(iterable, (function (a, i) {
    return iterable[i - 1] !== a
  }));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))

Can someone explain how this piece of code works? The output is a vector with the letters of input but without repetition.

var uniqueInOrder = function (iterable) {
  return [].filter.call(iterable, (function (a, i) {
    return iterable[i - 1] !== a
  }));
}
console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))
Share Improve this question edited Oct 3, 2015 at 13:02 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Oct 3, 2015 at 12:16 daymosdaymos 2033 silver badges8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Let's break this down: return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));

*. we are returning an Array.

*. using .filter.call(iterable, allows us to use the Array.prototype.filter method on the iterable which is a string (making the function treat the string as an array of chars) as the first parameter that call gets is the context.

*. the filter function returns a subset of the array for each element that returns true. so when doing return iterable[i - 1] !== a every time we check if the element in index i-1 which is basically the previous element is not equal to the current element which is a if it is not equal we return true so the a element is a part of the subset array which is being returned.

note that the easiest way for you to understand is debug just paste this code in the developer toolbar console:

 var uniqueInOrder = function (iterable)
    {debugger;
      return [].filter.call(iterable,(function (a, i) { return iterable[i - 1] !== a }));
    }
    console.log(uniqueInOrder("aaaaaBBBDSJJJJ"))

@daymos Callback is invoked with three arguments. See here.

发布评论

评论列表(0)

  1. 暂无评论