问题
Code will speak more plainly than I will:
var candidateIndex = 0;
var minValue = Number.MAX_VALUE;
topArray.every(function(element, index) {
if (element.innerArray && element.innerArray.length < minValue) {
minValue = element.innerArray.length;
candidateIndex = index;
if (minValue == 0) {
return false;
}
}
return true;
});
// ... use minValue and candidateIndex
What this is doing is going through the topArray, and finding either the first member of that array that has an innerArray of length 0, otherwise finding the one that has the smallest length innerArray. It's working fine, but the checker that I have accurately reports "Mutable variable is accessible from closure."
I see that that's usually a bad thing, particularly with asynchronous code. I've looked through How to avoid access mutable variable from closure and accessing mutable variable in an event closure, and understand that in those cases, the anonymous function is asynchronous, and it's desirable to store the state of the mutable variable at the time, but in my case, I want the synchronous anonymous function I invoke to change the variable.
In this case, the warning that I'm getting is wrong, and I should just ignore it, right? Outside of using a for loop instead of every, is there any way to get the functionality I want without the warning occuring?
Update: for what it's worth, the warning does seem to be coming from my WebStorm IDE itself, instead of any of the analysis tool plugins.
回答1:
Having gotten confirmation from the comments above that this warning is basically a false positive, I modified the code to ignore the warning message:
topArray.every(function(element, index) {
//noinspection JSReferencingMutableVariableFromClosure
if (element.innerArray && element.innerArray.length < minValue) {
minValue = element.innerArray.length;
candidateIndex = index;
//noinspection JSReferencingMutableVariableFromClosure
if (minValue == 0) {
return false;
}
}
return true;
});
(The warning only triggers when comparing the value, as opposed to when setting it.)
I'm eager to hear any other answers, but if I don't, I'll accept this answer in about a week.
来源:https://stackoverflow.com/questions/20533039/mutable-variable-is-accessible-from-closure-in-a-function-passed-to-array-prot