javascript - unique() 函数如何工作

标签 javascript arrays filter

当我查看一个 unique() 函数时,我发现了 它接受一个数组作为参数并返回一个新数组,其中包含该数组的唯一元素(这意味着没有重复的项目)。但是我无法理解这个函数的逻辑。有人能给我解释一下吗?

这是函数:

function unique ( array ) {
    return array.filter(function(a){
        return !this[a] ? this[a] = true : false;
    }, {});
}

我无法真正理解整个代码,尤其是 !this[a] ? this[a] = true : false; 以及作为第二个参数传递给 filter 的新对象 ({})。

最佳答案

让我们从 filter 开始:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

a 是您应用过滤器的数组的随机数。整个要点如下:

return !this[a] ? this[a] = true : false;

如果 this[a] 为 true,则 a 已经被处理过一次,并且已作为其属性之一添加到 this 中。否则,this[a] 为 false。因此,如果其否定结果为 true,则应返回当前的 a。此外,this[a] 将设置为 true,然后我们继续执行下一个 a

以下代码片段将帮助您了解 filter 的作用:

var numbers = [1,2,3,4,5];
var filteredNumbers = numbers.filter(function(number){
    console.log(number);
    return number > 2;
});
console.log(filteredNumbers);

下面的代码片段将向您展示 unique 函数中发生的情况:

function unique ( array ) {
  return array.filter(function(a){
    console.log(this);
    return !this[a] ? this[a] = true : false;
  }, {});
}

var array = [1,2,3,1,2,3,4,5,5,6];

console.log(unique(array));

I understand the basic logic of filter but what i dont is the {} passed as a 2nd argument and how each value is added to a new array with !this[a]

第二个参数是一个可选值,您可以将其传递给filter方法,并且当您的回调将被执行(检查我在开头提到的关于filter的链接)。你传递一个空物体到那里。当您在回调中使用关键字 this 时,您将引用此对象。这就是为什么代码第一次进入此方法时会返回 {}。检查第二个片段输出的第一行。

我将根据第二个片段解释您问题的第二部分。第一次进入时你有一个空对象(我指的是这个)并且处理的第一个数字是1。所以这个1将是未定义的。所以 !this[1] 为 true。因此,执行 ? 后的第一部分是一个赋值

this[1] = true.

现在 this 获取了它的第一个键 1,值为 true。此外,1 将从过滤器返回。 2 和 3 也会发生同样的情况。当我们到达 1 时,

!this[1] 

为 false,因为 this[1] 为 true。因此返回 false,并且现在不会将 1 添加到处理完数组所有元素后返回的数组中。

关于javascript - unique() 函数如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41534713/

相关文章:

javascript - 如何使用贝塞尔曲线沿路径动画化图像

javascript - 在 foreach 循环中添加一次标题

c - 我不明白为什么这个循环会卡住

java - 填写输入后打印int数组内容仅显示0

arrays - 如何查找/过滤具有最小正差的数组元素

javascript - Safari 上 Ajax 返回的 JSON 数据转换为 javascript 列表

javascript - 使用 ClassNotty 时未捕获的语法错误 : Unexpected token .

处理数组的对象的 Java 字符串表示形式

javascript - 从段落中查找特定单词

c# - 逐行分析,如果符合条件则存储,否则忽略