admin管理员组文章数量:1336367
filter Creates a new array with all elements that pass
the test implemented by the provided function.
>>> 'abc'.filter(function(e){return e!='b'})
TypeError: "abc".filter is not a function
>>> Array.prototype.filter.call('abc', function(e){return e!='b'})
["a", "c"]
>>> jQuery.isArray('abc')
false
filter Creates a new array with all elements that pass
the test implemented by the provided function.
>>> 'abc'.filter(function(e){return e!='b'})
TypeError: "abc".filter is not a function
>>> Array.prototype.filter.call('abc', function(e){return e!='b'})
["a", "c"]
>>> jQuery.isArray('abc')
false
Share
Improve this question
edited Apr 15, 2012 at 3:28
Pointy
414k62 gold badges594 silver badges628 bronze badges
asked Apr 15, 2012 at 3:22
kevkev
162k49 gold badges283 silver badges281 bronze badges
2
-
1
No clue.
Array.filter
doesn't exist. Did you meanArray.prototype.filter.call
? – Ry- ♦ Commented Apr 15, 2012 at 3:25 -
@minitech
Array.filter
exists in Firefox. – Pointy Commented Apr 15, 2012 at 3:27
2 Answers
Reset to default 5All array methods are generic; i.e., they work on any object with numeric properties plus a length
property. See the specification for Array.prototype.filter
, for example: note that the algorithm is phrased entirely in terms of things like
Let
lenValue
be the result of calling the[[Get]]
internal method ofO
with the argument"length"
.
or
Let
kPresent
be the result of calling the[[HasProperty]]
internal method ofO
with argumentPk
.
Array.filter
is a Firefox-specific extension, BTW. The cross-browser version is Array.prototype.filter.call
.
You can do this because Array.filter
1 is defined to be generic; you can call it on NodeList
s, for example. This is just a convenience to the developer. It also works on strings, because in modern browsers (everything except IE 8 and earlier), you can access characters in a string like you would indices of an array, and that's what filter
is based on, along with length
:
var str = "Hello, world!";
str[2] // 'l'
However, I wouldn't remend making use of this feature if you plan on supporting Internet Explorer 8 or earlier, because the ES5 shivs likely won't detect the fact that the context is a string, which will break things.
1 And all the other Array
methods. Except, once again, on Internet Explorer 8 and earlier.
本文标签: javascriptWhy I can call Arrayprototypefilter() on a object which is not an arrayStack Overflow
版权声明:本文标题:javascript - Why I can call Array.prototype.filter() on a object which is not an array? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742390833a2465955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论