Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  1] [ 4]  / answers: 1 / hits: 109595  / 13 Years ago, thu, october 13, 2011, 12:00:00

I want to compare each string in an Array with a given string. My current implementation is:



function startsWith(element) {
return element.indexOf(wordToCompare) === 0;
}
addressBook.filter(startsWith);


This simple function works, but only because right now wordToCompare is being set as a global variable, but of course I want to avoid this and pass it as a parameter. My problem is that I am not sure how to define startsWith() so it accepts one extra parameter, because I dont really understand how the default parameters it takes are passed. I've tried all the different ways I can think of and none of them work.



If you could also explain how the passed parameters to 'built in' callback functions (sorry, I dont know of a better term for these) work that would be great


More From » callback

 Answers
117

Make startsWith accept the word to compare against and return a function which will then be used as filter/callback function:



function startsWith(wordToCompare) {
return function(element) {
return element.indexOf(wordToCompare) === 0;
}
}

addressBook.filter(startsWith(wordToCompare));


Another option would be to use Function.prototype.bind [MDN] (only available in browser supporting ECMAScript 5, follow a link for a shim for older browsers) and fix the first argument:



function startsWith(wordToCompare, element) {
return element.indexOf(wordToCompare) === 0;
}

addressBook.filter(startsWith.bind(this, wordToCompare));






I dont really understand how the default parameters it takes are passed




There is nothing special about it. At some point, filter just calls the callback and passes the current element of the array. So it's a function calling another function, in this case the callback you pass as argument.



Here is an example of a similar function:



function filter(array, callback) {
var result = [];
for(var i = 0, l = array.length; i < l; i++) {
if(callback(array[i])) { // here callback is called with the current element
result.push(array[i]);
}
}
return result;
}

[#89621] Wednesday, October 12, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
malaysias

Total Points: 619
Total Questions: 110
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;