In the below code, variable text
is not accessible in the findTextToDelete
function (it generates an error)
array = ['a', 'b', 'removeThis', 'c'];
removeText("removeThis");
function removeText(text) {
array.splice(array.findIndex(findTextToDelete),1);
}
function findTextToDelete(element) {
return element === text;
}
I am able to get around this by creating a global variable 'globalText':
var globalText = "";
array = ['a', 'b', 'removeThis', 'c'];
removeText("removeThis");
function removeText(text) {
globalText = text;
array.splice(array.findIndex(findTextToDelete),1);
}
function findTextToDelete(element) {
return element === globalText;
}
console.log(array)
However I am trying to understand why the first method does not work.
It seems there must be a better way to do this. Is there a way to pass 'text' into the callback function?
Any help would be appreciated.