• Aucun résultat trouvé

Some Operations on Arrays

Dans le document Guide to HTML, JavaScript and PHP (Page 130-133)

There are some Array methods that are useful for the kinds of problems addressed in this  book.

5.2.1

Manipulating Stacks and Queues

Stacks  and  queues  are abstract data types  familiar  to  computer  science students. They  are  used  to  store  and 

retrieve data in a par-ticular way. A stack uses a last-in first-out (LIFO) data storage model. You can think of it  as a stack of dinner plates. You put new dinner plates on the top of the stack, and when you  retrieve a dinner plate, it always comes from the top of the stack. So, the last value added  on a stack is the first value retrieved.

A queue uses a first-in first-out (FIFO) data storage model. It operates like a queue   (a line, in American English) of people waiting. A new person joins the line at the end, and  people leave the line according to who has been in line the longest. So, a value removed  from the queue is always the “oldest” value.

JavaScript  arrays  provide  a  very  friendly  environment  for  implementing  stacks  and  queues because arrays can be resized dynamically, while a script is running. However, the  methods shown here for operating on stacks and queues may not work in all browsers. For  example, they don’t work in the internal browser supplied with the AceHTML freeware  used for developing the code in this book.1 You will just have to try the code to see if it  works with your browser.

1You  can  specify  an  external  browser  to  use  from  within  AceHTML,  to  replace  its  internal  browser.

116 5 Using Arrays in HTML/JavaScript

5

The push() and pop() methods are used for managing stacks and queues. push()  adds (“pushes”) the specified arguments to the end of the target array (the “top” of the  stack), in order, as you would for either a stack or a queue. The length  property is auto-matically updated. The pop() method (no calling arguments) removes (“pops”) the last  (most  recent)  element  from  the  array,  returns  the  value  of  that  element,  and  decreases  length by 1, as you would for a stack.

The shift() and unshift() methods are similar to push() and pop(), except  that they operate from the front (index 0) of an array. shift() (no arguments) removes  the first element from the array (as you would for a queue), returns the value of that ele-ment, shifts the remaining elements down one position, and decreases length by 1. The  unshift() method shifts current array elements up one position for each argument,  inserts its arguments in order at the beginning of the array, and increases length by 1 for  each argument. This action wouldn’t be used with either a stack or queue—it amounts to  allowing  “line  crashers.”  The  use  of  these  methods  might  seem  backwards  because  unshift() adds elements and shift() removes them.

To summarize:

For a queue: use push() to add a new value at the end of the queue and shift() to  remove the “oldest” value (the value at index 0).

For a stack: use push() to add a new value to the top of the stack and pop() to remove  a value from the top of the stack.

Documents 5.2 illustrates how to use these methods to treat an array first as a stack and  then as a queue.

Document 5.2 (stacksAndQueues.htm)

<html>

<head>

<title>Stacks and Queues</title>

<script language="javascript" type="text/javascript">

var a=[1,3,5,7], i;

// Treat the array like a stack.

document.write("STACK:" + a + " length of a = " + a.length+"<br />");

a.push(11,12,13); a.length+"<br />");

// Treat the array like a queue.}

document.write("QUEUE:" + a + " length of a = " + a.length+"<br />");

117 5.2 Some Operations on Arrays

a.push(11,12,13);

document.write(a + " length of a = " + a.length +"<br />");

for (i=1; i<=3; i++) { a.shift();

document.write(a + " length of a = " + a.length +"<br />");

</script>}

</head>

<body></body>

</html>

Note the use of an entire array name in the  document.write()  parameter  list.  This  automatically  displays  all  the  elements  of  the  array, separated by commas.

5.2.2 Sorting

Sorting array elements in ascending or descending order is a fundamental computing task. 

However, it can be challenging to write efficient sorting algorithms. (Understanding and  developing  sorting  algorithms  is  a  standard  topic  in  basic  computer  science  courses.)  Fortunately, JavaScript has an Array method, sort() , that will operate on arrays with-out much work on your part. Document 5.3 shows how to use this method to sort an array  in ascending order. Unfortunately, as you will see, this code does not produce the expected  result!

Document 5.3 (sort.htm)

<html>

<head>

<title>Sorting Arrays</title>

<script language="javascript" type="text/javascript">

var a=[7,5,13,3];

document.write(a + " length of a = " + a.length+"<br />");

a.sort();

document.write(a + " length of a = " + a.length+"<br />");

</script>

</head>

<body>

</body>

</html>

118 5 Using Arrays in HTML/JavaScript

5

The contents of the array are displayed before and after application of the sort()  method. The array is clearly not sorted, as 13 is not less than 3! It is apparent that the  sort() method has performed a “lexical” sort based on the order of characters in the  ASCII character sequence even when the characters represent numbers; the character “1” 

comes before the character “3” in this sequence in the same sense that “a” comes before 

“c” in the dictionary, and therefore, “ac” comes before “c.” This result would be easier to  understand if the values from the array came from a prompt() or from the input fields  of a form because it has already been demonstrated that “numbers” are treated like strings  of characters. However, for sorting arrays of user-defined numbers, this behavior is less  obvious and is clearly a potential disaster.

The sort() method can cause problems even with text. If, for example, you replace  the array declaration with

var a=["zena","David","apple","pie"];

the result is still probably not what you  intended.  Uppercase  letters  come  before  lowercase  letters  in  the  stan-dard  ASCII  character  sequence,  so 

“David” is still “less than” “apple.” 

The behavior of the sort() method constitutes a serious implementation problem. If  you are sorting just text, you could consider using the toUpperCase() or  toLower-Case() methods to convert all of the letters to either uppercase or lowercase letters prior  to  applying  the sort()  method,  but  this  isn’t  a  very  satisfying  solution  in  general.  

A more comprehensive solution is to supply the sort() method with your own code for  deciding whether one item is larger than, smaller than, or equal to another item in an array. 

This solution will be addressed in Chap. 6.

5.3

Dans le document Guide to HTML, JavaScript and PHP (Page 130-133)