It's crystal clear from the spec
Array.prototype.filter ( callbackfn [ , thisArg ] )
,
If athisArg
parameter is provided, it will be used as the this
value
for each invocation of callbackfn
.
So:
var arr = [0,1,2,true,4,{"abc":123},6,7,{"def":456},9,[10]];
arr.filter(Object.hasOwnProperty,"2222222");
translates to these calls, in sequence
"2222222".hasOwnProperty(0); // true -> 0
"2222222".hasOwnProperty(1); // true -> 1
"2222222".hasOwnProperty(2); // true -> 2
"2222222".hasOwnProperty(true); // false ->
"2222222".hasOwnProperty(4); // true -> 4
"2222222".hasOwnProperty({"abc":123}); // false ->
"2222222".hasOwnProperty(6); // true -> 6
"2222222".hasOwnProperty(7); // false ->
"2222222".hasOwnProperty({"def":456}); // false ->
"2222222".hasOwnProperty(9); // false ->
"2222222".hasOwnProperty([10]); // false ->
// filter() => [0,1,2,4,6]
The lines where it says true
are because strings can be indexed into like arrays, so a string with two characters has the indexes 0
and 1
as own properties.
Array.prototype.filter ( callbackfn [ , thisArg ] )
right in the header and "If athisArg
parameter is provided, it will be used as the this value for each invocation ofcallbackfn
." on paragraph later - How could it be any more clear than that? – Eclatit will be used as this value for each invocation
is not exaclty2+2=4
. – Voglerthis
value for each invocation", and not having encounteredthis
before in JS is strangely at odds with the ability to write lines likearr.filter(Object.hasOwnProperty,"2222222")
. (BTW, I didn't downvote, if you think that.) – Eclatthis
before in JS :) But I wasn't sure about how it is being used. Please check the discussion in below answer to understand why it may not be that straightforward. I am not worried about downvotes as much as long as I know how I can improve on my post. – Vogler