atar.yosef Posted September 2, 2012 Share Posted September 2, 2012 Hi there!!W3schools has demonstrated how to sort a numerical array using the following code: <code><script type="text/javascript">function sortNumber(a, {return a -b;}var arr = new Array(6);arr[0] = "10";arr[1] = "5";arr[2] = "40";arr[3] = "25";arr[4] = "1000";arr[5] = "1";document.write(arr + "<br />");document.write(arr.sort(sortNumber));</script></code>I just wanted to know how does the sortNumber() function work? What's the meaningful of the a,b parameters which are passed into the function? What are they intended to represent, and how does this snippet: a-b cause to sort the array numerical elements ascending? Link to comment Share on other sites More sharing options...
Ingolme Posted September 2, 2012 Share Posted September 2, 2012 Given any pair of elements in the array, if the return value is positive, A goes after B, if the return value is negative, A goes before B. If the return value is 0 their positions are not changed. 1 Link to comment Share on other sites More sharing options...
atar.yosef Posted September 2, 2012 Author Share Posted September 2, 2012 (edited) @ingolme:Thanks you very much about your response, but unfortunately, I didn't understand your words because you spoke too shortly. I didn't understand how does the a and b parameters that passed into the sortNumber() function represent an index in the array. Here they don't use the arr syntax so how can they access to the array's indices? Edited September 2, 2012 by atar Link to comment Share on other sites More sharing options...
Ingolme Posted September 3, 2012 Share Posted September 3, 2012 All of it happend inside the Javascript's engine.The sort() method takes the function you gave it and tries it on pairs of elements over and over until all of them are sorted. You tell it which of the pair is supposed to go first an which goes second with the algorithm you have in the function. Just imagine that the array only has two elements, A points to the first element and B points to the last one, you tell it which of the two should go first based on the value that they have. 1 Link to comment Share on other sites More sharing options...
atar.yosef Posted September 3, 2012 Author Share Posted September 3, 2012 @ingolme:Thank you about your detailed explanation!! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now