阵列过滤器返回奇怪的结果 [英] Array filter returns strange results

查看:158
本文介绍了阵列过滤器返回奇怪的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

相关<一个href=\"http://stackoverflow.com/questions/36232576/how-to-filter-object-using-array-prototype-filter\">this的问题,我想尝试这种

Related to this question, i wanted to try out this

var arr = [0,1,2,true,4,{"abc":123},6,7,{"def":456},9,[10]];
arr.filter(Object.hasOwnProperty,"abc");//outputs [0, 1, 2]
arr.filter(Object.hasOwnProperty,"2222222") //[0, 1, 2, 4, 6]

有谁知道为什么过滤器返回这些值? 过滤的规格和的 MDN文档也没有明确告诉多么第二个参数滤波器的使用。

Does anyone knows why filter return these values? Spec of filter and MDN doc also doesn't clearly tell how second argument of filter is used.

推荐答案

的第二个参数的 Array.prototype.filter 是将被设置为<$值C $ C>这个到作为第一个参数传递的功能。

The second argument to the Array.prototype.filter is the value that will be set as this to the function that is passed as a first argument.

所以你的code最终是这样的:

So your code ends up to be something like:

arr.filter(function(v, i, a) {
    return Object.hasOwnProperty.call("222", v, i, a);
});

因此​​,它基本上检查,如果222字符串有你在数组中枚举的属性。

So it basically checks if the "222" string has the properties you enumerate in the array.

从它变得清楚为什么性能 0 1 2 被发现 - 因为这些是在222串,并说, 9 {ABC:123} 不 - 因为222字符串没有这样的属性。

From that it becomes clear why properties 0, 1 and 2 are found - since those are the indexes of the characters in the "222" string, and, say, 9 or {"abc":123} are not - since "222" string does not have such a properties.

这是同样的故事与较长的字符串,其中还包括性能 4 6 只是因为它的长

It is the same story with the longer string, which also includes properties 4 and 6 just because it's longer.

一些例子:

Object.hasOwnProperty.call("222", 1); // true, because `"222"[1]` is there
Object.hasOwnProperty.call("222", 'foo'); // false, because `"222"['foo']` is not there

这篇关于阵列过滤器返回奇怪的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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