Zepto使用array.filter [英] Zepto's use of array.filter

查看:97
本文介绍了Zepto使用array.filter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力提高我对Javascript的理解,所以我一直在浏览Zepto库。我遇到过这一行:

I am trying to boost my Javascript understanding, so I've been looking through the Zepto library. I came across this line:

uniq = function(array){
    return array.filter(function(item, idx){
        return array.indexOf(item) == idx
    })
}

这个功能的目的是什么?据我所知,它正在创建一个新的,独特的元素阵列,对吧?但它本质上只是克隆数组吗?如果是这样, array.slice()会不会更快?

What is the purpose of this function? From what I can tell, it is creating a new, unique array of elements, right? But isn't it essentially just cloning the array? If so, wouldn't array.slice() be faster?

最后,它不会提高性能将 array.indexOf(item)更改为 array.indexOf(item,idx)?或者更好的是,只需返回true ?什么时候 array.indexOf(item)== idx 等于是吗?这是为了防止重复的项目?但是什么时候会发生呢?

Finally, wouldn't it increase performance to change array.indexOf(item) to array.indexOf(item,idx)? Or better yet, just return true? When does array.indexOf(item)==idx not equal true? Is this to prevent duplicate items? But when would that ever actually happen?

推荐答案

它正在创建一个新的,独特的元素数组,对吗?

它只是过滤你的数组元素以返回唯一元素。

It just filter your array elements to return unique elements.

演示

但是它不是基本上只是克隆数组吗?

不,如上所述。

如果是这样,array.slice()会不会更快?

Slice不会删除重复项。

Slice doesn't remove duplicates.

最后,将array.indexOf(item)更改为array.indexOf不会提高性能(项,IDX)?或者更好的是,只返回true?

如果只返回true,则无法确定元素是否重复。

If you only return true you won't identify if the element is duplicated or not.

演示

array.indexOf(item)== idx什么时候不等于true?

示例:

我有以下数组:

Example:
I have the following array:

['10','20 ','30','20','10']

迭代次数


  • 1: array.IndexOf(10)== 0 ? //是的,所以返回true

  • 2: array.IndexOf(20)== 1 ? //是的,所以返回true

  • 3: array.IndexOf(30)== 2 ? //是的,所以返回true

  • 4: array.IndexOf(20)== 3 ? //不,因为 array.indexOf(20)是1,所以返回false

  • 5:数组。 IndexOf(10)== 4 ? //不,因为 array.indexOf(10)是2,所以返回false

  • 1: array.IndexOf(10) == 0 ? // yes, so return true
  • 2: array.IndexOf(20) == 1 ? // yes, so return true
  • 3: array.IndexOf(30) == 2 ? // yes, so return true
  • 4: array.IndexOf(20) == 3 ? // no because array.indexOf(20) is 1 , so return false
  • 5: array.IndexOf(10) == 4 ? // no because array.indexOf(10) is 2 , so return false

所以,当元素已被发现时,它会变错,因为索引不一样。

So, when the element has already been found it gets false because the indexes are not the same.

这篇关于Zepto使用array.filter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆