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 mean Array.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
Add a ment  | 

2 Answers 2

Reset to default 5

All 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 of O with the argument "length".

or

Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.


Array.filter is a Firefox-specific extension, BTW. The cross-browser version is Array.prototype.filter.call.

You can do this because Array.filter1 is defined to be generic; you can call it on NodeLists, 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