Jquery every loop returns false, but does not end the function

I have a function that takes a string separated by a dot and parses it into an array. And I want to encode these elements of the array and check the value greater than 255 and return false, if you do not continue to work with operators and return true as the end of the function. But it never stops the loop and always returns true.

Here is the code:

checkipAddress = function(value){//instance value: 999.999.999.999 result:true debugger var array = value.split('.'); $.each(array, function(index,val){ debugger if(parseInt(val)>255) return false; // it should end the loop and exit function with return false. }); return true; } 
+6
source share
1 answer

The return from one function does not magically do the one that called it, and even more so uses a certain return value.

If you want to do this, you need to set the variable that the external function will use:

 checkipAddress = function(value){ var rv = true; // <=== Default return value var array = value.split('.'); $.each(array, function(index,val){ if(parseInt(val)>255) return rv = false; // <=== Assigns false to `rv` and returns it }); return rv; // <=== Use rv here } 

Side note. Your function will happily allow IP strings like "0.-234343.-1.0" and "1foo.2foo.3foo.4foo" . You might think:

 checkipAddress = function(value){ var rv = true; // <=== Default return value var array = value.split('.'); $.each(array, function(index,str){ str = $.trim(str); var val = +str; if(!str || val < 0 || val > 255) return rv = false; // <=== Assigns false to `rv` and returns it }); return rv; // <=== Use rv here } 

This is slightly better, but it also does not check if there are exactly four parts for IP and allows values ​​such as "1.1e2.3.4" (exponent notation). And all this, of course, is specific to IPv4, while we are entering the world of IPv6 ...

If you are using IPv4, if your goal is to make sure that it is a 4-component IPv4 address in the usual form, I would spit on the regular expression:

 checkipAddress = function(value){ var rv; var match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(value); var n, part; if (match) { rv = true; for (n = 1; rv && n < 5; ++n) { part = +match[n]; // We know it not blank from the regex if (part > 255) { // We know it not negative or fractional from the regex rv = false; } } } else { rv = false; } return rv; } 

Or in modern browsers (or using a suitable Array#every pad):

 checkipAddress = function(value){ var match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(value); rv = !match ? false : Array.prototype.slice.call(match, 1).every(function(entry) { // We know it not blank, negative, or fractional from the regex return +entry <= 255; }); return rv; } 
+10
source

Source: https://habr.com/ru/post/986647/


All Articles