为什么里面的回报值不同?功能之外?

时间:2018-05-07 06:27:56

标签: javascript arrays filter

我正在尝试探索thisArg& filter数组方法&只是试验thisArg如何使用&从filter返回。我有一个数组,在filter方法内,我正在检查thisArg中是否存在该值,如果没有,则推送值&最后从数组过滤器函数返回thisArg

在过滤器功能中,日志thisArg将显示[1],[1,2],...,但如果有重复的元素,则不会被推送。

在安慰从filter返回时,重复的值仍然存在。

我无法理解thisArg方法内外filter值的差异。

thisArg是可选值。在以下函数中

array.filter(function(item) {}, []) // this empty array is thisArg



var x = [1, 2, 3, 4, 1];

var m = x.filter(function(item) {
  if (this.indexOf(item) === -1) {
    this.push(item)
  }
  // it will console [1],[1,2],[1,2,3]....
  // will never have repeated value
  console.log("Before Final Return ", this);
  return this; // returning this expecting it will not have repeated value

}, [])
// this will have [1,2,3,4,1]
console.log("Final Value ", m)




1 个答案:

答案 0 :(得分:2)

filter期望返回值为true或false。数组总是很简洁。看起来你的意思是:

var x = [1, 2, 3, 4, 1];
var m = [];

x.forEach(function (item) {
  if (this.indexOf(item) === -1) {
    this.push(item)
  }
}, m);

console.log("Final Value ", m)

相关问题