473,800 Members | 2,726 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Please help me understand this simple function

RC
http://www.w3schools.com/jsref/tryit...tryjsref_sort2

You can see above link or read below i copy/paste from above link

<script type="text/javascript">

function sortNumber(a, b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "5"
arr[4] = "1000"
arr[5] = "1"

document.write( arr + "<br />")
document.write( arr.sort(sortNu mber))

</script>

Please help me to understand the last line:

arr.sort(sortNu mber)

The function sortNumber has TWO parameters a and b pass in.
I just can't understand how the array 0 to 5 pass thire
values into there to sort.

Please explain to me. Thank Q!
Jun 7 '06 #1
2 2190
On Wed, 07 Jun 2006 13:38:25 -0400, RC wrote:
http://www.w3schools.com/jsref/tryit...tryjsref_sort2

You can see above link or read below i copy/paste from above link

<script type="text/javascript">

function sortNumber(a, b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "5"
arr[4] = "1000"
arr[5] = "1"

document.write( arr + "<br />")
document.write( arr.sort(sortNu mber))

</script>

Please help me to understand the last line:

arr.sort(sortNu mber)

The function sortNumber has TWO parameters a and b pass in.
I just can't understand how the array 0 to 5 pass thire
values into there to sort.

Please explain to me. Thank Q!


The main work of the sorting is done by the Array.sort() function. Part of
sorting is you need a way of knowing for a pair of elements which one
should be above, and which one should be below. If you were always sorting
by number, or by string order, the sort function wouldn't need any
parameters, and it would be just 'array.sort()'. But this would mean
having lots of different sort functions for different kinds of thing, so
instead it asks you to provide a function which is given a pair of objects
and returns a result saying whether the first is less than, equal to, or
greater than the second, which is what sortNumber does.

sortNumber isn't called by the array itself - it's called repeatedly by
the sort method every time it needs to decide which array element to put
first.

Jun 7 '06 #2
RC wrote:
function sortNumber(a, b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "5"
arr[4] = "1000"
arr[5] = "1"

document.write( arr + "<br />")
document.write( arr.sort(sortNu mber))

Please help me to understand the last line:

arr.sort(sortNu mber)

The function sortNumber has TWO parameters a and b pass in.
I just can't understand how the array 0 to 5 pass thire
values into there to sort.


In arr.sort(sortNu mber), 'sortNumber' is not a function call but just a
reference to the function that had been defined above. The sort()
function will then use the function provided (sortNumber) anytime it
needs to compare two elements (to sort an array, you need to have a way
to compare any two of its elements).

Most of the power of javascript is in this ability to use functions as
real objects, which makes it a very different language from the whole
Algol family, from C to java (and much more pleasant to work with).

To illustrate, take the following:

<script type="text/javascript">

function addTo(anObject)
{
anObject.field= 'here!';
return anObject;
}

function example(anObjec t, aFunction)
{
aFunction(anObj ect);
}

function exampleReturn()
{
return arguments[1](arguments[0]);
}

var o1={};
example(o1, addTo);
document.write( o1.field+'<br>' ); // 'here!'

var o2={};
document.write( exampleReturn(o 2, addTo).field+'< br>'); // 'here!'

</script>

Notice, in the second example, that 'return' works normally, returning
the value of the function call. In the first example, function 'example'
just ignores the value it receives from the call, returning itself
'undefined'.

On a completely unrelated note, notice that 'exampleReturn' doesn't
define its arguments. Instead, they are accessed through the 'arguments'
object. In practice, when you define the arguments of a function, you're
just giving aliases to the elements of 'arguments'. Among other things,
this allows a function to have a variable number of arguments, even if
they are named:
<script type="text/javascript">

function sumTo(anObject)
{
// Same as 'if(!anObject) anObject={};'
anObject = anObject || {};
anObject.sum=0;
for(var i=1; i<arguments.len gth; ++i)
anObject.sum += arguments[i];
return anObject;
}

var s1={otherField: 'otherValue'};
sumTo(s1, 1, 2, 3, 4);
document.write( s1.sum+'<br>'); // '10'
document.write( s1.otherField+' <br>'); // 'otherValue'

var s2=sumTo(null, 2, 6);
document.write( s2.sum+'<br>'); // '8'
document.write( s2.otherField+' <br>'); // 'undefined'

var s3=sumTo();
document.write( s3.sum+'<br>'); // '0'

</script>

In the first case, a variable is created, with an initialised field, and
sumTo is called with 4 numbers. They are summed, put in a new 'sum'
field (if there had beena previous one, it would have been overwritten),
and the object is returned.

In the second case, no object is passed to sumTo, only a list of
numbers, so it creates a new object. As there was no 'otherField' to
begin with, writing it to output yields 'undefined'.

The third case is a variant of the second in which nor arguments are
supplied at all, so the function just builds the object, initalises the
sum. the loop stops before it even begins, and the object is returned.

Notice the use of anObject with boolean operators (!, ||, etc).
Javascript typecasts null, undefined, "" and 0 to false.
This can be both handy and tricky.
--
am

laurus : rhodophyta : brezoneg : smalltalk : stargate
Jun 7 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

35
4557
by: wired | last post by:
Hi, I've just taught myself C++, so I haven't learnt much about style or the like from any single source, and I'm quite styleless as a result. But at the same time, I really want nice code and I go to great lengths to restructure my code just to look concise and make it more manageable. When I say this, I'm also referring to the way I write my functions. It seems to me sometimes that I shouldn't have many void functions accepting...
2
1906
by: kevin | last post by:
hi there I am struggling with javascript. Can you please help me I've managed to get the get URL in flash to open a html that has the function that opens the Feedback form I want. I Couldn't get the feedback form to load directly from the flash because I had to use the function in dreamweaver that opens it with the specifications I wanted. That being just a simple box with no menus etc...
9
1742
by: SB | last post by:
Ok, very simple problem. I'm trying to update a value by calling a function using pass by reference, but it does not update the value. In short, the value I'm trying to update is balance, which is a private member of the class Account. I have a public function called getBalance(). I have another public function called deposit, which I pass the balance (by calling getBalance() using pass by reference) and a second value for the amount of...
3
1273
by: pointBoarder | last post by:
So I have this query that returns ID Item Quantity primary text int unique I have a form with a command button that runs a function, but I need the function to be able to tally the quantity for each unique item.
16
1583
by: hoggmeister | last post by:
Hi, Im new to C coming from a java background. I having difficulty adjusting to C and was hoping someone could help me with a little simple code to get started. I would like a little program that outputs on to the console a message like "please enter some text" then when the user enters text it gets stored in a char array or whatever is best. I then want to check that the array is no longer than 25 chars ( i dont know if malloc is...
4
1691
by: gs | last post by:
I have searched Google, MSDN,... for a week. I am still unable to make available functions in my csharp dll as native windows functions for some legacy non dotnet application I just want to expose the regex function to my old legacy application built with some tools that runs a VM with capability to access windows native DLL via declaration syntax like public int function setRegexp(String argRegexp) alias "ClassIeString.setRegexp"
13
2151
by: sd00 | last post by:
Hi all, can someone give me some coding help with a problem that *should* be really simple, yet I'm struggling with. I need the difference between 2 times (Target / Actual) However, these times will fall somewhere between a Start & End time Further more, there will be Break & Lunch times between Start & End. Example... Start 08:00 Break start 10:30
5
3376
by: Y2J | last post by:
I am working through this book on C++ programming, the author is speaking of using linked lists. He gave and example which I found confusing to say the least. So I rewrote the example in a way that I could better understand the concept, he was trying to convey to me. I ran my own example and it crashed and burn "what a surprise!" : (. I ran the authors example out of the book and quess what, it crashed also, : 0. I ran them both on my...
11
1783
by: Daniel T. | last post by:
The function below does exactly what I want it to (there is a main to test it as well.) However, I'm curious about ideas of making it better. Anyone interested in critiquing it? void formatText( const string& in, int charsPerLine, int lines, vector< string >& out ) { out.resize( 1 ); out = ""; int prev = 0;
0
9691
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10507
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10255
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9092
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7582
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6815
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4150
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3765
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2948
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.