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.