Data structures and Algorithms (Hedgehog book) reading notes (1)----array

Source: Internet
Author: User
Tags shallow copy javascript array

In JavaScript, an array is actually a special object, and the index used to represent the offset is the property of that object, so the JavaScript array is essentially an object. At the same time, these numeric indexes are internally converted into string types because the property names in the JavaScript object must be strings. In addition, the JavaScript array has a feature that each item of the array can hold any type of data, and that the size of the array can be dynamically adjusted.

1. Creating an array

There are two ways to create an array, and the first is to simply declare an array variable:

var numbers = []; var numbers = [1, 2, 3, 4, 5]

Because the array is a special object, the third is to create an array by calling the constructor of the array.

var New Array (); var New Array (1, 2, 3, 4, 5);

Using the [] operator to declare an array variable is considered more efficient, it is recommended to use this method.

2. Integer operation of the array

The replication of arrays is divided into two types: latent and deep. Since the array is a special object, assigning the array to a variable is only a reference to the array in the past. If the value of the array is modified by reason, all variables referencing the array are modified to the new value. So when copying an array, a better approach is to copy it deep, create a new array, copy each element in the existing array to the new array, and then complete the replication.

Shallow copy:

var nums = [];  for (var i = 0; i <; + +i) {    = i + 1;} var samenums = nums;nums[0] =;p rint (samenums[//  

Deep copy:

function copy (arr1, arr2) {    for(var i = 0; i < arr1.length; + +i)        {=  arr1[i];< c8/>}}var nums = [];  for (var i = 0; i <; + +i) {    = i + 1;} var samenums = [];copy (Nums, samenums); nums[0] =;p rint (samenums[// 1
3. Array-dependent method 3.1 generates an array from a string

The split () method that invokes the string object can generate an array, pass the delimiter in the method, and then split the string into an array based on the delimiter.

3.2 Finding an array

IndexOf (): Returns the first index of the same element as the parameter.

LastIndexOf (): Returns the index of the last element in the same element.

Returns 1 if the same element is not found.

Here is a basic way to find a method, that is, if it is not found, it will usually return-1, not other messy things.

3.3 String representation of an array

There are two ways to convert an array to a string: Join () and toString (). In addition, when you use the print () function directly on an array, the system automatically calls the ToString () method of that array.

3.4 Merging multiple arrays

The concat () function can combine multiple arrays to create a new array. The initiator of the method is an array, and the argument is another array. All the elements in the parameter are connected to the array that calls the Concat () method.

3.5 Adding a DELETE element to an array

add elements:push () and unshift ()

Delete elements:pop () and Shift ()

Universal Method:Splice ()

Note: These methods operate directly on the original array.

Push () Adds an element to the end of the array, and unshift () adds the element at the beginning of the array. Pop () deletes the element at the end of the array, and SHIFT () deletes the first element of the array.

The splice method can provide three parameters: 1. Start index

2. Number of elements to delete

3. Elements you want to add into the array

By using these three parameters reasonably, you can add or delete an element. At the same time, the splice () function returns an array of deleted elements, so it can also be used to intercept a new array from an existing array. However, it is important to note that the method modifies the original array, so you should consider whether you want the original array to change when you use it as an intercept array.

Examples of three uses of splice () are provided below

To add an element:

var nums = [1, 2, 3, 7, 8, 9]; var newelements = [4, 5, 6];nums.splice (3, 0//  [1, 2, 3, [4, 5, 6], 7, 8, 9]

Note: In this case, the element that you want to add into the array, if it is a group, the entire array will be treated as if an element was added to the array, rather than adding the elements in the array.

If you want to insert multiple elements, you can write this:

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

To delete an element:

var nums = [1, 2, 3, +, 4, 5];nums.splice (3, 4//  1,2,3,4,5

To intercept an array:

var num = [1, 2, 3, 4, 5, 6, 7, 8]; var somenum = Num.splice (3, 3); var remainnum =//  4,5,6//  1,2,3,7,8
3.6 Sorting for arrays

There are two sorting-related algorithms: reverse () and sort (). Reverse () flips the order of the elements in the array. Sort () allows incoming comparison functions and sorts the array.

When no arguments are passed in the sort () function, whether it is a string or a number, the elements are sorted in dictionary order:

var names = ["David", "Mike", "Cynthia", "Clayton", "Bryan", "Raymond"//  Bryan,clayton, Cynthia,david,mike,raymondvar nums = [3, 1, 2, 4,$//  1,100,2,200,3,4

If you want to sort by numeric size, you can pass in a function that is larger than the size:

function Compare (NUM1, num2) {    return num1- num2;} var nums = [3, 1, 2, 4,$//  1,2,3,4,100,200

The passed-in function should return a positive or negative value, and if positive, the first argument is preceded by the second argument, whereas the second argument precedes it.

3.7 Iterator Method 3.7.1 iterator method that does not generate a new array

foreach (): Accepts a function as an argument and uses the function for each element in the array.

Every (): accepts a function that returns a Boolean type, using the function for each element in the array. If all the elements make the function return True, the function returns True.

Some (): accepts a function that returns a Boolean type that returns True whenever an element causes the function to return true.

Reduce (): Accepts a function that returns a value. The method starts with an accumulated value and calls the function continuously on the accumulated values and subsequent elements in the array, until the last element in the arrays, and finally returns the resulting accumulated value. The function accepted by reduce () accepts two parameters, the first parameter is the value that has been accumulated so far, and the second parameter is now the value.

Reduceright (): Executes from right to left.

3.7.2 iterator method for generating a new array

Map (): Takes a function as a parameter and returns a new array whose elements are the result of applying that function to the original element.

Filter (): Takes a function as a parameter, returning all elements that enable the function to return true.

4. Two-dimensional and multidimensional arrays

There is no two-dimensional array in JavaScript, but you can implement a two-dimensional array by inserting array elements into the array.

var twod = []; var rows = 5;  for (var i = 0; i < rows; + +i)    {= [];}

With regard to how to create a two-dimensional array, a best practice is mentioned in the book, which is a 64-page example of javascript:the good Parts (O ' Reilly) .

 Array.matrix = function   (NumRows, Numcols,    Initial) { var  arr = [];  for  (var  i = 0; i < numrows; ++i) { Span style= "COLOR: #008000" >//  set line  var columns = [];  for  (var  j = 0; j < Numcols; ++j) { Span style= "COLOR: #008000" >//  set column  columns[j] = initial;    } Arr[i]  = columns;  return   arr;}  

This creates a NumRows row, a two-dimensional array of numcols columns that can be accessed through arr[i][j] to each of these elements.

If you are working with elements in a two-dimensional array, you can also access each element and manipulate each element through this nested loop, where it is important to note that loop parameters are best referred to arr.length for looping, so that even jagged arrays can be handled well.

5. Objects and Arrays

An array can also contain objects, which can also contain arrays, which makes the array more widely used.

Data structures and Algorithms (Hedgehog book) reading notes (1)----array

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.