18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8<br />

The highlighted block of code contains an if statement testing which array has more items (if they are<br />

equal, no changes are necessary). Both branches of the if statement do the same thing on different<br />

arrays: The first adds zeroes to aVersion2, whereas the second adds zeroes to aVersion1. After this<br />

point, both arrays have an equal number of digits.<br />

The final step is to iterate through the arrays and compare the corresponding digits in each array:<br />

function compareVersions(sVersion1, sVersion2) {<br />

var aVersion1 = sVersion1.split(“.”);<br />

var aVersion2 = sVersion2.split(“.”);<br />

if (aVersion1.length > aVersion2.length) {<br />

for (var i=0; i < aVersion1.length - aVersion2.length; i++) {<br />

aVersion2.push(“0”);<br />

}<br />

} else if (aVersion1.length < aVersion2.length) {<br />

for (var i=0; i < aVersion2.length - aVersion1.length; i++) {<br />

aVersion1.push(“0”);<br />

}<br />

}<br />

for (var i=0; i < aVersion1.length; i++) {<br />

}<br />

if (aVersion1[i] < aVersion2[i]) {<br />

return -1;<br />

} else if (aVersion1[i] > aVersion2[i]) {<br />

return 1;<br />

}<br />

return 0;<br />

}<br />

In this section, a for loop is used to compare the arrays. If a digit in aVersion1 is less than the corresponding<br />

digit in aVersion2, the function automatically exits and returns –1. Likewise, if the digit in<br />

aVersion1 is greater than the one from aVersion2, the function exits and returns 1. If all digits are<br />

tested and no value has been returned, the function returns 0, meaning that the two versions are equal.<br />

This function is used like this:<br />

alert(compareVersions(“0.9.2”, “0.9”)); //returns 1<br />

alert(compareVersions(“1.13.2”, “1.14”)); //returns –1<br />

alert(compareVersions(“5.5”, “5.5”)); //returns 0<br />

The first line returns 1 because 0.9.2 is greater than 0.9; the second line returns –1, because 1.13.2 is less<br />

than 1.14; the third line returns 0 because the two versions are equal. This function is used extensively in<br />

this chapter.<br />

236

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!