Return only true or false in JavaScript/JQuery $.each code
I am working on some JavaScript/jQuery code that detected a user agent based against a list of specified user agents retrieved via a JSON request.
As soon as a match is found I want the function to return false and to break out of the loop, only continuing to return true if none of the user agents in the JSON document were found.
I have this code...
function checkUserAgent() {
$.getJSON('noapplet-use开发者_运维问答ragents.json', function(data) {
$.each(data, function(key, val) {
if(navigator.userAgent.search(new RegExp(val)) != -1) {
console.log("False!");
return false;
}
});
console.log("True!");
return true;
});
}
// ... call to checkUserAgent() function
However, when false is returned; true is also returned. How can I make the first return stop the function, as necessary.
The console.log()
statements are just their temporarily for Firebug.
Edit: Thanks to all for their feedback. I could not add comments for some reason.
As I said in my comment, you cannot return a value from an Ajax call. You have to pass a callback:
function checkUserAgent(callback) {
$.getJSON('noapplet-useragents.json', function(data) {
var result = true;
$.each(data, function(key, val) {
if(navigator.userAgent.search(new RegExp(val)) != -1) {
console.log("False!");
result = false;
return false;
}
});
callback(result);
});
}
and call it with:
checkUserAgent(function(result) {
// so something with the result
});
One option is for your checkUserAgent
function to handle callbacks. This code would work:
var checkUserAgent = function(callback){ //callback is the function
$.getJSON('noapplet-useragents.json', function(data) {
$.each(data, function(key, val) {
if(navigator.userAgent.search(new RegExp(val)) != -1) {
console.log("False!");
callback(true);
}
});
callback(false);
}
精彩评论