JavaScript Arrays and Lists tutorial

Source: Internet
Author: User
Tags abstract arrays data structures prev shallow copy trim javascript array

javascript: array



Arrays are the most common data structure in the programming world. Arrays are included in any programming language, with only slight differences in form. Arrays are built-in types in programming languages and are usually very efficient. Data storage that can meet different needs, this chapter will explore the working principle of arrays in javascript and their use cases.

One: the definition of array in javascript

The standard definition of an array is: a linear collection of stored elements. Elements can be arbitrarily stored by index. The index is usually a number that is used to calculate the offset of the storage position between the elements. Almost all programming languages have similar data structures. However, javascript is slightly different.

Array in JavaScript is a special kind of object. The index used to indicate the offset is a property of the object. The index may be an integer. However, these numeric indexes are converted to string types internally because the attribute names in the javascript object must be strings. Arrays are a special kind of object in JavaScript, so they are not as efficient as in other languages.

Arrays in JavaScript, strictly speaking, should be called objects, which are special JavaScript objects and are classified internally as arrays. Since Array is treated as an object in JavaScript, it has many properties and methods used in programming.

Two: using arrays

Arrays in JavaScript are very flexible. But there are many ways to create arrays and access elements. You can also search and sort the array in different ways. JavaScript 1.5 also provides functions that allow programmers to use functional programming techniques when working with arrays.

1. Create an array

The easiest way is to declare an array variable with the [] operator.

var numbers = [];

Creating an array this way will result in an empty array of length zero. You can also prove this with the built-in length.

console.log (numbers.length); // 0

Another way is to put a set of elements directly inside the [] operator when declaring an array.

var numbers = [1,2,3,4,5]
console.log (numbers.length); // 5

You can also create an array by calling the constructor of Array

var numbers = new Array ();
console.log (numbers.length); // 0

You can also pass a set of elements to the constructor as the initial value of the array

var numbers = new Array (1,2,3,4,5)
console.log (numbers.length)

Finally, when calling the constructor, you can pass only one parameter to specify the length of the array.

var numbers = new Array (10);
console.log (numbers.length); // 10
console.log (numbers); // []

A common feature in scripting languages is that the elements in an array do not have to be of the same data type, which is different from other programming languages as follows:

var objects = [1, "joe", true, null];

You can call Array.isArray () to determine whether an object is an array. Demonstrated as follows

var numbers = 3;
var arr = [7,4,123];
console.log (Array.isArray (numbers)); // false
console.log (Array.isArray (arr)) // true

The array creation method we discussed in this section is the best way. Most JavaScript experts recommend using [], which is considered more efficient than the Array constructor.

2. Read and write arrays

In an assignment statement, you can use the [] operator to assign data to an array. For example, the following loop assigns a number from 1 to 100 to an array.

var num = [];
for (var i = 0; i <100; ++ i) {
    num [i] = i + 1
    
};
console.log (num)

You can also use the [] operator to read the elements in an array, as follows:

var numbers = [1,2,3,4,5]
var sum = numbers [0] + numbers [1] + numbers [2] + numbers [3] + numbers [4];
console.log (sum) // 15

To get all the elements in an array in order, it is easier to use a for loop.

var numbers = [1,2,3,5,8,13,21];
var sum = 0;
for (var i = 0; i <numbers.length; i ++) {
    sum + = numbers [i]
}
console.log (sum); // 53

3. Generate an array from a string

You can also generate an array by calling the string object split () method. This method divides a string into parts by some common delimiters, such as separating spaces of words, and saves each part as an element in a newly created array.

The following code demonstrates the use of split ().


var sent = "the quik brown fox jumped over zhe lazy dog";
var word = sent.split ("")
console.log (word); // ["the", "quik", "brown", "fox", "jumped", "over", "zhe", "lazy", "dog"]
for (var i = 0; i <word.length; ++ i) {
    word [i]
    console.log ("word" + i + ":" + word [i])
}


4. Integral operations on arrays

Several operations are performed as a whole. First, you can assign an array to another array:

var nums = [];
for (var i = 0; i <10; ++ i) {
    nums [i] = i + 1;
}
var sam = nums;
console.log (sam)

However, when an array is assigned to another array, only a new reference is added to the assigned array. When you change the value of the array through the original reference, another reference will also feel the change. The following code illustrates this situation.


var nums = [];
for (var i = 0; i <100; + i) {
    nums [i] = i + 1;
}
var sament = nums;
nums [0] = 400;
console.log (sament [0]) // 400


This copy is called shallow copy. The new array will still point to the original array. A better solution is deep copy. Each element of the original array is copied to the new array. You can write a method to copy the function. Do this

function arr_copy (arr1, arr2) {
    for (var i = 0; i <arr1.length; i ++) {
        arr2 [i] = arr1 [i]
    }
}

var nums = [];
for (i = 0; i <100; i ++) {
    nums [i] = i + 1;
}

var sament = [];
arr_copy (nums, sament);
nums [0] = 400;
console.log (sament [0]) // 1


Three: access function

JavaScript provides a set of functions for accessing array elements, called accessor functions, which return some variant of the target array.

1. Find elements

The indexof () function is one of the most commonly used access functions to find out whether the parameters passed in exist in the target array. If the parameter exists in the objective function, returns the element index in the array. If not, it returns -1. Indexof () is case sensitive

If the array contains multiple identical elements, indexof () returns the index of the first element with the same arguments. There is another function with similar function, lastIndexOf (). This function returns the index of the last element of the same element. If no identical element is found, it returns -1. As follows. Indexof () is case sensitive

var str = "Hello world!"
console.log (str.indexOf ("Hello"))
console.log (str.indexOf ("World"))
console.log (str.indexOf ("world"))

If the array contains multiple identical elements, indexof () returns the index of the first element with the same arguments. There is another function with similar function, lastIndexOf (). This function returns the index of the last element of the same element. If the same element is not found, it returns -1. As follows


var names = ["David", "Mike", "Cynthia", "Mike", "Jennifer"];
var name = "Mike";
var firstPos = names.indexOf (name);
console.log (firstPos) // 1

var lastPos = names.lastIndexOf (name)

console.log (lastPos) // 3


2. String representation of the array

There are two methods to convert an array into a string: join () and toString (). Both methods return a string containing all the elements of the array, with each element separated by a comma. Here are some examples

var names = ["David", "Mike", "Cynthia", "Mike", "Jennifer"];
var namestr = names.join ();
namestr.toString ();
console.log (namestr); // David, Mike, Cynthia, Mike, Jennifer


3. Create a new array from an existing array

The concat () and splice () methods allow creating new arrays from existing arrays. The concat method can combine multiple arrays to create a new array, and the splice () method intercepts a subset of an array to create a new array.

Let's first take a look at how the concat method works. The method initiator is an array and the parameters are another array. As an array of parameters, all elements of which are concatenated behind the array that calls the concat () method. The working principle of the concat () method is shown below.


var cisDept = ["Mike", "Clayton", "Terrill", "Danny", "Jennifer"];
var dmpDept = ["Ramondy", "Cynthia", "Bryan"];
var itDiv = cisDept.concat (dmpDept);
console.log (itDiv) // ["Mike", "Clayton", "Terrill", "Danny", "Jennifer", "Ramondy", "Cynthia", "Bryan"]

itDiv = dmpDept.concat (cisDept)
console.log (itDiv); // ["Ramondy", "Cynthia", "Bryan", "Mike", "Clayton", "Terrill", "Danny", "Jennifer"]


The output is

Mike, Clayton, Terrill, Danny, Jennifer, Ramondy, Cynthia, Bryan

Ramondy, Cynthia, Bryan, Mike, Clayton, Terrill, Danny, Jennifer

The splice () method intercepts a new array from an existing array. The first parameter of the method is the starting index of the truncation, and the second parameter is the length of the truncation. The following program shows how the splice () method works:

var itDiv = ["Mike", "Clayton", "Terrill", "Danny", "Jennifer", "Cynthia", "Bryan"];
var dmpDept = itDiv.splice (3,3) // ["Danny", "Jennifer", "Cynthia"]

var cisDept = itDiv;

// ["Mike", "Clayton", "Terrill", "Bryan"]

There are other uses of the splice () method, such as adding or removing elements from an array. For details, please refer to:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

4. Variable function


There is a set of variable functions in JavaScript. Using them, you can change the contents of the array without referring to an element in the array. These functions are usually simplified. Make difficult things easy.

Adding elements to an array

There are two methods for adding elements to an array, push () and unshift (). The push () method adds an element to the end of the array.

var nums = [1,2,3,4,5];
nums.push (6)
console.log (nums); // [1, 2, 3, 4, 5, 6]

You can also use the length property of an array to add elements to the array, but push () looks more intuitive.

var nums = [1,2,3,4,5];
nums [nums.length] = 6;
console.log (nums)

Compared with adding elements at the end of the array, it is more difficult to add elements at the beginning of the array. If it is not conducive to the variable function provided by the array, after the new elements are added, each subsequent element needs to be moved backward accordingly A position. The following code illustrates this process.


var nums = [111,2,3,4,5,22,2]
var newnum = 1;
var _n = nums.length;
for (var i = _n; i> = 0; --i) {
    nums [i] = nums [i-1]
}
nums [0] = newnum;
console.log (nums) // [1, 111, 2, 3, 4, 5, 22, 2]


But as more and more elements are stored in the array, the above code becomes more inefficient.

The unshift () method can add elements to the beginning of the array. The following code shows the use of this method.


var nums = [2,3,4,5,6]
var newnum = 1;
nums.unshift (newnum);


var nums2 = [3,4,5];
nums2.unshift (newnum, 1,2)
console.log (nums2); // [1, 1, 2, 3, 4, 5]


The second occurrence of unshift () shows that it can be called once to add multiple elements to the array.

2. Remove elements from the array

Use the pop () method to remove the last element of the array:

var nums = [1,2,3,4,5,9]
nums.pop ()
console.log (nums)

If there is no mutable function, removing the first element from the array requires moving subsequent elements one position forward each

var nums = [9,1,2,3,4,5,6];
for (var i = 0; i <nums.length; ++ i) {
    nums [i] = nums [i + 1]
}

In addition to moving subsequent elements forward by one, there is one more element.



The shift () method can delete the first element in the array. The following code shows its usage.

var nums = [11,1,2,3,4,5,6,7];
nums.shift ();
console.log (nums)

The extra comma at the end of the array disappeared. The pop () and shift () methods both return the deleted element as the method return value, so you can use a variable to hold the deleted element.

var nums = [7,1,2,3,4,5,6];
var _d = nums.shift ();
nums.push (_d)
console.log (nums) // [1, 2, 3, 4, 5, 6, 7]

3. Add and remove elements from the middle of the array

Deleting the first element of an array has the same problem as adding an element at the beginning of the array. Both operations need to move the remaining elements in the array forward or backward. However, the splice () method can help us perform any of them. Kind of operation.

To add elements to an array using the splice () method, you need to provide the following parameters

Starting index
The number of elements to be added (the parameter is 0 when adding elements)
Elements to add to the array

var nums = [1,2,3,7,8,9]
var newElement = [4,5,6]
nums.splice (3,0, newElement)

The array to be inserted does not have to be organized into an array, it can be any sequence of elements

var nums = [1,2,3,7,8,9]
nums.splice (3,0,11,22,3,4,5)
console.log (nums); // [1, 2, 3, 11, 22, 3, 4, 5, 7, 8, 9]


Below is an example of splice () method removing elements from an array

var nums = [1, 2, 3, 11, 22, 3, 4, 5, 7, 8, 9]
nums.splice (3,3)
console.log (nums); // [1, 2, 3, 4, 5, 7, 8, 9]

4. Sort the array.

The two remaining methods are sorting the array. The first method is reverse (), which reverses the elements in the array. The following example shows this usage.

var nums = [1,2,3,4,5,6]
nums.reverse ();
console.log (nums); // [6, 5, 4, 3, 2, 1]

Sorting an array is a common requirement. If the element is a string type, then the array's variable method sort () becomes very easy to use.

var names = ["David", "Mike", "Cynthia", "Mike", "Jennifer"];
names.sort ();
console.log (names); // ["Cynthia", "David", "Jennifer", "Mike", "Mike"]

However, if the array elements are numeric, the sorting of the sort () method is less satisfying.

var nums = [3,1,2,100,4,200]
nums.sort ()
console.log (nums); // [1, 100, 2, 200, 3, 4]

The sort () method sorts the elements when sorting according to the dictionary. Therefore, it will determine that the elements are all string types. In the previous example, even if the elements are numeric types, they will be considered string types. In order for the sort () method to also sort the elements of the numeric type, you can pass a function of a relatively large size when calling the method. When sorting, the sort () method will compare the sizes of the two array elements.

For numeric types, this function can be a simple subtraction operation, subtracting one number from another. After figuring this out, we will do the following:

function compare (num1, num2) {
    return num1-num2;
}
var nums = [3,1,2,100,4,200]
nums.sort (compare);
console.log (nums); // [1, 2, 3, 4, 100, 200]

5. Iterator method

Finally, iterator methods, which apply a function to each element in an array, can return a value, a set of values, or a new array.


1. Iterator method that does not generate a new array.
The first set of iterators we discussed did not produce any new arrays. Instead, they either performed some operation on each element in the array or returned a value.

The first method in this group is forEach (), which takes a function as a parameter and uses it for each element in the array.

function square (num) {
    console.log (num, num * num);
}
var nums = [1,2,3,4,5,6,7,8,9,10]
nums.forEach (square);

Another iterator method is everyone (). This method accepts a function whose return value is a boolean, and uses this function for each element in the array. If the function returns true for all elements, this method returns true. Here is an example:


function isEven (num) {
    return num% 2 == 0;
}

var nums = [2,4,6,8,10];
var even = nums.every (isEven);
if (even) {
    console.log ("All are even")
} else {
    console.log ("Not all even numbers")
}



The some () method also accepts a function that returns a boolean type. This method returns true as long as one element makes the function return true.

function isEven (num) {
    return num% 2 == 0;
}
var nums = [1,2,4,5,6,7,8,9,10]
var someEven = nums.some (isEven);
console.log (someEven)

The reduce () method accepts a function and returns a value. This method starts with an accumulated value, and continuously calls the function on the accumulated value and subsequent elements in the array until the last element in the array, and finally returns the obtained accumulated value. The following example shows how to use reduce ()

function add (num1, num2) {
    return num1 + num2;
}
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce (add);
console.log (sum); // 55


The reduce () method and the add () function, from left to right, sum the elements in the array in order. The execution process is as follows:


add (1,2)-> 3
add (3,3)-> 6
add (6,4)-> 10
add (10,5)-> 15
add (15,6)-> 21
add (21,7)-> 28
add (28,8)-> 36
add (36,9)-> 45
add (45,10)-> 55



The reduce () method can also be used to concatenate the elements of an array into a long string.

function concat (accString, item) {
    return accString + item;
}
var words = ['the', 'quick', 'brown', 'fox'];
var sentence = words.reduce (concat)
console.log (sentence); // the quick brown fox

JavaScript also provides a reduceRight () method. Unlike reduce (), it executes from right to left. The following program uses the reduceRight () method to flip the elements in an array.

function concat (accString, item) {
    return accString + item;
}
var words = ['the', 'quick', 'brown', 'fox'];
var sentence = words.reduceRight (concat)
console.log (sentence); // fox brown quick the

2. Iterator method to generate a new array

There are two iterator methods to generate new arrays: map () and filter (). map () is a bit like forEach (). Use a function for each element in the array. The difference between the two is that map () returns a new array whose elements are the result of applying a function to the original elements. An example is given below:

function curve (grade) {
    return grade + = 5;
}
var grades = [1,3,5,8,10];
var newgrades = grades.map (curve);
console.log (newgrades)

Here is an example of using the map () method on a string array:


function first (word) {
    return word [0]
}

v
ar words = ['for', 'your', 'information'];
var acronym = words.map (first);
console.log (acronym.join ("")); // fyi



filter () is similar to every (), passing in a function that returns a boolean type. Unlike the every () method, when this function is applied to all elements in the array, when the result is true, the method does not return true, but returns a new array. This group contains the elements whose result is true. Below is an example.


function isEven (num) {
    return num% 2 == 0;
}

function isOdd (num) {
    return num% 2! = 0;
}

var nums = [];
for (var i = 0; i <20; ++ i) {
    nums [i] = i + 1;
}
console.log (nums)

var events = nums.filter (isEven)
console.log (events); // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

var odds = nums.filter (isOdd);
console.log (odds); // [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]



Here is an interesting example of using the filter () method


function passing (num) {
    return num> = 60;
}
var grades = [];
for (var i = 0; i <20; ++ i) {
    grades [i] = Math.floor (Math.random () * 101);
}
console.log (grades); // [4, 56, 87, 62, 24, 54, 80, 7, 95, 98, 40, 43, 56, 79, 84, 52, 87, 23, 43, 18]
var passGardes = grades.filter (passing);
console.log (passGardes); // [87, 62, 80, 95, 98, 79, 84, 87] random



Of course, you can also use filter () to filter an array of strings. The following example shows those words that do not contain "cie":


function after (str) {
    if (str.indexOf ("cie")> -1) {
        return true
    }
    return false;
}
var words = ["recieve", "deceive", "percieve", "deceit", "concieven"];
var nocie = words.filter (after);
console.log (nocie); // ["recieve", "percieve", "concieven"]



Six, two-dimensional and multi-dimensional arrays

JavaScript only supports one-dimensional arrays, but by storing array elements in the array, you can easily create multi-dimensional arrays. This section will discuss how to create a two-dimensional array in javascript.

1. Create a two-dimensional array

A two-dimensional array is similar to a data table consisting of rows and columns. To create a two-dimensional array in JavaScript, you need to create an array, and then make each element of the array an array. At the very least, we need to know how many rows the 2D array will contain. With this information, we can create a 2D array with n rows and 1 column.

var twod = [];
var row = 5;
for (var i = 0; i <row; ++ i) {
    twod [i] = [];
}
console.log (twod); // [Array [0], Array [0], Array [0], Array [0], Array [0]]

The problem with this is that every element in the array is undefined. A better way is to add a new method to the javascript array object by extending it. This method sets the number of rows, columns, and initial values of the array according to the parameters passed in. The following is the definition of this method;


Array.matrix = function (numrows, numcols, initial) {
    var arr = [];
    for (var i = 0; i <numrows; ++ i) {
        var columns = [];
        for (var j = 0; j <numcols; ++ j) {
            columns [j] = initial;
        }
    arr [i] = columns
    }
    return arr;
}



Here is some test code for this test method:

var nums = Array.matrix (5,5,0);
console.log (nums [1] [1]); // 0

var names = Array.matrix (3,3, "");
console.log (names)
names [1] [2] = "Joe";

You can also use a line of code and a set of initial values to initialize a two-dimensional array

var grades = [[1,35,1], [123,52,14], [123,12,5,21,5,2]]

For small-scale data, this is the easiest way to create a two-dimensional array.

2. Processing elements of a two-dimensional array

There are two most basic ways to process the elements in a two-dimensional array: access by column and access by row.

For both methods, we use a set of embedded for loops. For column-by-column access, the outer loop is for rows, and the inner loop is for columns.

Take the array grades as an example, each row records the performance of a student. We can add up all the students' grades and divide by the number of subjects to get the average grade for that student. The following code illustrates this process.


var grades = [[89,77,78], [76,62,81], [91,94,89]];
var total = 0;
var average = 0.0;
for (var row = 0; row <grades.length; ++ i) {
    for (var col = 0; col <grades [row] .length; ++ col) {
        total + = grades [row] [col]
    }

    average = total / grades [row] .length;
    console.log ("Student" + parseInt (row + 1) + "average:" + average.toFixed (2));
    total = 0;
    average = 0.0;



The inner loop is controlled by this expression;

col <grades [row] .length

This expression has multiple lines because each line is an array. We can use the length property of the array to determine how many lines each line contains.

Student1 average: 81.33
Student2 average: 73.00
Student3 average: 91.33

For row-wise access, you only need to slightly adjust the order of the for loop so that the outer loop corresponds to the column, and the memory loop corresponds to the row. The following procedure calculates the grades of each subject for a student.


var grades = [[89,77,78], [76,62,81], [91,94,89]];
var total = 0;
var average = 0.0;
for (var col = 0; col <grades.length; ++ col) {
    for (var row = 0; row <grades [col] .length; ++ row) {
        total + = grades [row] [col]
    }

    average = total / grades [col] .length;
    console.log ("Test" + parseInt (col + 1) + "average" + average.toFixed (2));

    total = 0;
    average = 0.0;
}



Output

Test 1average 85.33
Test 2average 77.67
Test 3average 82.67

3. Hierarchical arrays

An array with different levels is the number of elements in each row of the exponent group. Many programming languages do not perform well when dealing with such arrays, but JavaScript performs well because the length of each row can be calculated.

To give an example, suppose that the number of grade records of each student in the array grades is different. You can still correctly calculate the correct average score without modifying the code.


var grades = [[89,77], [76,82,81], [91,94,89,99]];
var total = 0;
var average = 0.0;
for (var row = 0; row <grades.length; ++ row) {
    
    for (var col = 0; col <grades [row] .length; ++ col) {
        total + = grades [row] [col];
    }

    average = total / grades [row] .length;
    console.log ("Student" + parseInt (row + 1) + "average" + average.toFixed (2));

    total = 0;
    average = 0.0;
}



Note that the first student has two courses, the second student has three courses, and the third student has four courses. Because the program calculates the length of each array in the inner for loop, even if the length of each row in the array is not the same, the program will not have any problems. The program output is:

Student1 average 83.00
Student2 average 79.67
Student3 average 93.25



Seven, array of objects

So far, the arrays discussed in this chapter have only contained elements of basic data types, such as numbers and strings. Arrays can also contain objects, and the methods and properties of arrays still apply to objects.

Consider the following example:


function Point (x, y) {
    this.x = x;
    this.y = y;
}

function displayPts (arr) {
    for (var i = 0; i <arr.length; ++ i) {
        console.log (arr [i] .x + "," + arr [i] .y);
    }
}
var p1 = new Point (1,2);
var p2 = new Point (3,5);
var p3 = new Point (2,8);
var p4 = new Point (4,4);
var points = [p1, p2, p3, p4]

for (var i = 0; i <points.length; ++ i) {
    console.log ("Point" + parseInt (i + 1) + ":" + points [i] .x + "," + points [i] .y)
}

var p5 = new Point (12, -3);

points.push (p5)
displayPts (points);

points.shift ();
console.log (points)

displayPts (points)



Use the push () method to add point (12, -3) to the array, and use the shift () method to remove (1,2) from the array.

Eight, the array in the object.

In objects, you can use arrays to store complex data. Many count Data can be implemented as an object, and the object uses an array to store data.

In the following example, we create an object to store the observed maximum temperature data. The object has two methods. One method is to add a new temperature record, and the other method is to calculate the average stored in the object. air temperature. code show as below


function weekTemps () {
    this.dataStore = [];
    this.add = add;
    this.average = average;
}

function add (temp) {
    this.dataStore.push (temp)
}

function average () {
    var total = 0;
    for (var i = 0; i <this.dataStore.length; ++ i) {
        total + = this.dataStore [i];
    }
    return total / this.dataStore.length;
}

var thisWeek = new weekTemps ();
thisWeek.add (52);
thisWeek.add (55);
thisWeek.add (61);
thisWeek.add (65);
thisWeek.add (55);
thisWeek.add (50);
thisWeek.add (52);
thisWeek.add (49);
console.log (thisWeek.average ()); // 54.875



The add () method uses the array's push () method to add elements to the array dataStore. Why is this method called add () instead of push ()? This is because an intuitive name is a very useful technique when customizing methods (not everyone knows what it means to push an element, but everyone adds what an element means.)



javascript: list


In daily life, people often use lists: to-do list, shopping list, top ten list, last ten list and so on. Computers also use lists, especially when there are too many elements in the list. Lists are particularly useful when you don't need to find or sort elements in a long sequence. Conversely, if the data structure is very complicated, the list is not so useful.

This chapter shows that if you create a simple list class, we first give the list an abstract data type definition, then describe how to implement the abstract data type (ADT), and finally, analyze several practical problems that lists are suitable for solving.

First, the abstract data type definition of the list

In order to design the abstract data type of the list, you need to give the definition of the list, including what attributes the list should have, and what operations should be performed on the list.

A list is an ordered set of data, and the data items in each list are called elements. In javascript, the elements in a list can be of any data type. There is no limit to how many elements can be stored in the list (the actual use will be limited by the program memory).

A list that contains no elements is called an empty list. The number of elements in a list is called the length of the list. In the internal implementation, a variable listSize is used to save the number of elements in the list. You can append an element at the end of the list, or insert an element at the beginning of the list. Use the remove method to remove elements from the list, and use the clear method to clear all the elements in the list.

You can also use the toString () method to display all the elements in the list, and use the getElement () method to display the current element. The list has attributes that describe the position of the element. The list has front and back (front and end). Use the next () method to move from the current element to the next element, and use the prev () method to move the current element to the previous element. You can also use the moveTo (n) method to move directly to the specified position. The currPos attribute represents the current position in the list.

The abstract data type of a list does not specify the storage structure of the list. In the implementation of this chapter, we use a dataStore to store the elements.

Abstract data definition for a list.


listSize (attribute) the number of elements in the list
pos (attribute) the current position of the list
length (property) returns the number of elements in the list
clear (method) clears all elements from the list
toString (method) returns the string form in the list
getElement (method) returns the element at the current position
insert (method) insert a new element after an existing element
append (method) adds a new element to the end of the list
remove (method) removes an element from the list
front (method) sets the current element in the list to the first element
end (method) moves the current element position in the list to the last
prev (method) Move the current position backward
next (method) advances the current position by one
currPos (method) returns the current position of the list
moveTo (method) moves the current position to the specified position

Second, implement the list class

Based on the list abstract data type defined above, you can directly implement a List class. Let's start by defining the constructor, although it is not itself part of the list abstract data type.


function List () {
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = []; // Create an empty array to hold the elements of the list
    this.clear = clear;
    this.find = find;
    this.toString = toString;
    this.insert = insert;
    this.append = append;
    this.remove = remove;
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.length = length;
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.getElement = getElement;
    this.contains = contains;
}



1.append: Add elements to the list

The first method we implemented was append (), which adds a new element to the next position in the list, which is exactly equal to the value of the variable listSize.

function append (element) {
    this.dataStore [this.listSize ++] = element;
}

When the new element is in place, the listSize of the variable is increased by 1.

2.remove: remove an element from the list

Let's see how to remove an element from the list. The remove () method is a difficult method to implement in the List class. First, find the element in the list, and then delete it. And adjust the underlying array object to fill the gap left after deleting the element. The good news is that you can use the splice () method to simplify this process. Let's start with a helper method find (), which is used to find the element to delete.

3.find find an element in the list

The find () method iterates through the array object dataStore to find the given element. If found, returns the position of the element. If not found, it returns -1. This is the standard value returned when no elements are found in the array. We can use this value for error checking in the remove () method.

The remove method uses the position returned by the find () method to intercept the array dataStore. After the array is changed, the value of the variable listSize is decremented by 1. To reflect the latest length of the list. Returns true if the element was deleted successfully, otherwise returns false.


function remove (element) {
    var foundAt = this.find (element);
    if (foundAt> -1) {
        this.dataStore.splice (foundAt, 1);
        --this.listSize;
        return true;
    }
    return false;
}



4. How many elements are in the length list

length () returns the number of elements in the list.

function length () {
    return this.listSize;
}

5.toStirng: display elements in the list

You can now create a method to display the elements in the list. Here is a short piece of code that implements the toString () method.

function toString () {
    return this.dataStore;
}

Strictly speaking, this method returns an array, not a string, but its purpose is to display the current state, so returning an array is sufficient.

Let's temporarily test the currently implemented code to verify the method we created earlier.


var names = new List ();
names.append ('Hammer');
names.append ('Niu Niu');
names.append ('doudou');
console.log (names.dataStore); // "" Hammer "," Niu Niu "," Dou "
names.remove ('Niu Niu');

console.log (names.dataStore); // ["锤 锤", "豆豆"]



6.insert: insert an element into the list

The next method we will discuss is insert (). What if I delete "Niu Niu" from the previous list and now want to put it back in place? The insert () method needs to know where the element is inserted (therefore, the current implementation is assuming that after inserting into an element in the list and knowing that it is fully written, you can define the insert () method).


function insert (element, after) {
    var insertPos = this.find (after);
    if (insertPos> -1) {
        this.dataStore.splice (insertPos + 1, 0, element);
        ++ this.listSize;
        return true
    }
    return false;
}



In the implementation process, the insert () method uses the find () method. The find () method will find the position of the passed after parameter in the list. After finding the position, use splice () to get the element inserted at that position. Then increase the variable listSize by 1 and return true. It indicates that the insertion was successful.

7.clear: Clear all elements in the list.

Next, we need a way to empty all the elements in the list and make room for inserting new elements.

function clear () {
    delete this.dataStore;
    this.dataStore = [];
    this.listSize = this.pos = 0;
}

The clear () method uses the delete operator to delete the array dataStore and then creates a new empty array. The last line sets the listSize and pos values to 0, indicating an empty new list.

8. Determine if the given value is in the list

The contains () method becomes useful when you need to determine whether a given value is in a list. Here is the method definition:


function contains (element) {
    for (var i = 0; i <this.dataStore.length; ++ i) {
        if (this.dataStore [i] == element) {
            return true;
        }
    }
    return false;
}



9. Traversing the list

The last set of methods allows the user to move freely on the list, and the last method getElement () returns the current element of the list


function front () {
    this.pos = 0;
}

function end () {
    this.pos = this.listSize
- 1;
}

function prev () {
    if (this.pos> 0) {
        --this.pos;
    }
}

function next () {
    if (this.pos <this.listSize-1) {
        ++ this.pos;
    }
}

function currPos () {
    return this.pos;
}

function moveTo (position) {
    this.pos = position;
}

function getElement () {
    return this.dataStore [this.pos]
}



Now we create a list of names to show how to use it.


var names = new List ();
names.append ('Hammer');
names.append ('Niu Niu');
names.append ('doudou');
names.append ('Sheep');
names.append ('Tutu');
names.append ('Hana');



Now move to the first element in the list and display it.

names.front ();
console.log (names.getElement ()); // Show "Hammer"

Next move one unit forward and display it:

names.next ();
console.log (names.getElement ()); // Display "牛牛"

The code above shows that these behaviors are actually the concept of an iterator, which is what we will discuss next.

3. Use iterators to access lists

Iterators eliminate the need for internal storage of relational data. In order to traverse the list. The aforementioned methods fornt (), end (), prev (), next (), and currPos implement an iterator of the List class. Here are some advantages of using iterators over the way you use array indexes.

Don't care about the underlying data storage structure when accessing list elements
When you add an element to the list, the index value is wrong. In this case, you only need to update the list, not the iterator.
The List class can be implemented with different types of data storage, and iterators provide a unified way to access the elements in the list.

With these advantages in mind, I use an iterator to iterate through the list:

for (names.front (); names.currPos () <names.length (); names.next ()) {
    console.log (names.getElement ())
}

At the beginning of the for loop, set the current position in the list to the first element. As long as the value of currPos is less than the length of the list, it will continue to loop, each time the loop calls the next () method to move the current position forward by one.

Similarly, you can also traverse the list from back to front, the code is as follows:

for (names.front (); names.currPos ()> = 0; names.prev ()) {
    console.log (names.getElement ())
}


The loop starts at the last element of the list. When the current position is greater than or equal to 0, the prev () method is called to move backward by one position.

Iterators are only used to move around the list at will, and should not be used with people and methods for adding or removing elements from the list.

Fourth, a list-based application.

Read text

To show how to use lists, we implement a rental self-service query system similar to Redbox.

var _movies = "(1) RogueTrader (" Devil's Salesman ") NNN (2) TradingPlaces (" Upside Down ") NNN (3) WallStreet (" Wall Street ") NNN (4) WallStreet2: MoneyNeverSleeps (" Wall Street 2: Money Never Sleeps " 》) NNN (5) BoilerRoom Members ") NNN (9) AmericanPsycho (" American Mental Patient ") NNN (10) BonfireoftheVanities"
var movies = _movies.split ("NNN");

The split () program above splits a string into an array, with one extra space. Although one extra space is harmless, it is a disaster when comparing strings. Therefore, we need to use the trim () method in the loop to delete the end of each array element. Space. It would be great if there was a function that encapsulates these operations.


function createArr (file) {
  var arr = file.split ("NNN");
  for (var i = 0; i <arr.length; ++ i) {
     arr [i] = arr [i] .trim ();
  }
  return arr;
}



2. Use list to manage video rental

Let's save the array to a list, the code is as follows:

var movieList = new List ();

for (var i = 0; i <movies.length; ++ i) {
    movieList.append (movies [i])
}

Now you can write a function to display the list of discs:

function displayList (list) {
    for (list.front (); list.currPos () <list.length (); list.next ()) {
        console.log (list.getElement ())
    }
}

The displayList () function has no problems with native data types, such as a list of strings. But it doesn't need custom types. For example, we will define the Customer object below. Let me modify it slightly so that it can discover that the list is composed of Customer objects. This can be displayed accordingly. Here is the redefined displayList () function:


function displayList (list) {
    for (list.front (); list.currPos () <list.length (); list.next ()) {
        if (list.getElement () instanceof Customer) {
            console.log (list.getElement () ['name'] + "," +
                list.getElement () ["movie"]
                );
        }

        else {
            console.log (list.getElement ())
        }
    }
}



For each element in the list, the instanceof operator is used to determine whether the element is a Customer object. If so, use name and movie for indexing. Get the value checked out by the customer. If not, just return the element.

Now that you have movies, you need to create a new list, Customers, to store customers who check out movies in the system:

var customers = new List ();

The list contains a Customer object consisting of the user's name and the user's checked out movie. Below is the constructor for the Costomer object.

function Customer (name, movie) {
    this.name = name;
    this.movie = movie;
}

Next, you need to create a movie function that allows the user to check out. This function takes two parameters: the client name and the movie the client wants to check out. If the movie is currently available for rental, this method will remove the element from the list and also add customers to the customer list. This operation will use the contains () method of the list.

Here is the function used to check out the movie:


function checkout (name, movie, filmList, customerList) {
    if (movieList.contains (movie)) {
        var c = new Customer (name, movie);
        customerList.append (c);
        filmList.remove (movie)
    }
    else {
        console.log (movie + "is not available")
    }
}



Let's test the checkout function with simple code


var movies = createArr (_movies);
var movieList = new List ();
var customers = new List ();
for (var i = 0; i <movies.length; ++ i) {
    movieList.append (movies [i])
}

// show xx
displayList (movieList)

checkout ("RogueTrader", "Trader", movieList, customers);
// xx

displayList (customers)



As for the list method, we have updated to this point and can add more robust methods to implement it according to our own needs.

Symbol: test code


function List () {
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = []; // Create an empty array to hold the elements of the list
    this.clear = clear;
    this.find = find;
    this.toString = toString;
    this.insert = insert;
    this.append = append;
    this.remove = remove;
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.length = length;
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.getElement = getElement;
    this.contains = contains;
}

// Add elements to the list
function append (element) {
    this.dataStore [this.listSize ++] = element;
}

// find find method
function find (element) {
    for (var i = 0; i <this.dataStore.length; ++ i) {
        if (this.dataStore [i] == element) {
            return i;
        }
    }
    return -1;
}

// remove method
function remove (element) {
    var foundAt = this.find (element);
    if (foundAt> -1) {
        this.dataStore.splice (foundAt, 1);
        --this.listSize;
        return true;
    }
    return false;
}

// length
function length () {
    return this.listSize;
}

// toString
function toString () {
    return this.dataStore;
}

// insert
function insert (element, after) {
    var insertPos = this.find (after);
    if (insertPos> -1) {
        this.dataStore.splice (insertPos + 1, 0, element);
        ++ this.listSize;
        return true
    }
    return false;
}

// clear
function clear () {
    delete this.dataStore;
    this.dataStore = [];
    this.listSize = this.pos = 0;
}

// contains determines whether the given value is in the list
function contains (element) {
    for (var i = 0; i <this.dataStore.length; ++ i) {
        if (this.dataStore [i] == element) {
            return true;
        }
    }
    return false;
}

function front () {
    this.pos = 0;
}

function end () {
    this.pos = this.listSize-1;
}

function prev () {
    if (this.pos> 0) {
        --this.pos;
    }
}

function next () {
    if (this.pos <this.listSize-1) {
        ++ this.pos;
    }
}

function currPos () {
    return this.pos;
}

function moveTo (position) {
    this.pos = position;
}

function getElement () {
    return this.dataStore [this.pos]
}

// var names = new List ();
//names.append('Hammer ');
//names.append ('牛牛');
//names.append('doudou ');
//names.append ('羊羊');
//names.append('Rabbit ');
//names.append ('花花');

//console.log(names.dataStore);

//names.front ();
//console.log(names.getElement());//Show "hammer"

//names.next ();

//console.log (names.getElement ()); // Show "doudou"

// for (names.front (); names.currPos () <names.length (); names.next ()) {
// console.log (names.getElement ())
//}

var _movies = "(1) RogueTrader (" Devil's Salesman ") NNN (2) TradingPlaces (" Upside Down ") NNN (3) WallStreet (" Wall Street ") NNN (4) WallStreet2: MoneyNeverSleeps (" Wall Street 2: Money Never Sleeps " 》) NNN (5) BoilerRoom (`` Boiling Water Room '') NNN (6) GlengarryGlen Ross (`` Baijin Family '') NNN (7) Enron: TheSmartestGuysInTheRoom (`` Enron Storm: Smart Men in the House '') NNN (8) Trader (`` Trading Members)) NNN (9) AmericanPsycho ("American Mental Patient") NNN (10) BonfireoftheVanities ("Vanity of the Fire");

function createArr (file) {
  var arr = file.split ("NNN");
  for (var i = 0; i <arr.length; ++ i) {
     arr [i] = arr [i] .trim ();
  }
  return arr;
}

var movies = createArr (_movies)

// Save the array to a list
var movieList = new List ();

for (var i = 0; i <movies.length; ++ i) {
    movieList.append (movies [i])
}

//console.log(movieList)
var customers = new List ();

// Show video list
function displayList (list) {
    for (list.front (); list.currPos () <list.length (); list.next ()) {
        if (list.getElement () instanceof Customer) {
            console.log (list.getElement () ['name'] + "," +
                list.getElement () ["movie"]
                );
        }

        else {
            console.log (list.getElement ())
        }
    }
}

//displayList(movieList.dataStore)

function Customer (name, movie) {
    this.name = name;
    this.movie = movie;
}

// The function to check out the movie
function checkout (name, movie, filmList, customerList) {
    if (movieList.contains (movie)) {
        var c = new Customer (name, movie);
        customerList.append (c);
        filmList.remove (movie)
    }
    else {
        console.log (movie + "is not available")
    }
}

displayList (movieList)













































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.