"Data structure and algorithm JavaScript description"--An array reading guide:
This article is relatively long, introduced the array of common operation methods and some considerations, and finally a few classic exercises (interview questions).
Definition of the array:
An array in JavaScript is a special object that represents an index of an offset that is a property of that object, which is likely to be an integer. However, these numeric indexes are internally converted to string types because the property name in the JavaScript object must be a string. is classified internally as an array. Because the Array is treated as an object in JavaScript, it has many properties and methods that can be used during programming.
Using arrays:
1. Create an array
- Using the [] operator, var arr=[], the method is the most efficient.
- Call the constructor of array to create an array, var myarr=new arrery ()
2. Read and write arrays
3. Generates an array from a string that invokes the split () method of the String object.
The split () method splits a string object into an array of strings by splitting it into substrings.
Str.split ([separator][, limit])
separator Specifies the character (string) used to split the string. Separator is a string or regular expression.
- When ignoring separator, returns an array of the entire string.
- When separator is an empty string, STR returns an array of each character in the original string.
Limit "Optional" an integer that limits the number of split fragments returned, and the returned array captures up to a limit of one element.
/* Defines a function that splits a string into an array of strings using the specified delimiter. After separating the string, the function outputs the original string information in turn, the delimiter used, returns the number of array elements, and returns all the elements in the array. */function splits (str, separator) { var afterstring = str.split (separator); Console.log (' Pre-split string: ' + str + ' "'); Console.log (' separator: ' + separator + ' "); Console.log (' Split to get: '); for (var i = 0; i < afterstring.length; i++) Console.log (Afterstring[i] + ",");} var eg1 = "Hello World"; var eg2 = "A,b,c,d"; var eg3 = "";//defines STR as an empty string, var eg1separator = ""; When separator is an empty string, Str is converted to an array of characters in the string. var eg2separator = ","; var eg2separator = ","; Splits (EG1, eg1separator); splits (EG1, eg2separator); splits (EG1);//Ignore Separator, the array form of the entire string is returned. Splits (EG2, eg2separator); splits (eg3);//Returns an array containing an empty string instead of an empty array.
4. Integral operation of an array: (one of the questions)
Shallow copy: assigns array A to array B, at which point the array B is only a reference to array a, and as it changes, array b changes as well.
var a=[];for (var i=0;i< 5;i++) { a[i]=i;} var b=a;console.log (a[1]); Console.log (b[1]);//Assignment reference before 1a[1]=999;console.log (A[1]), Console.log (b[1]);//assignment reference after 999
Deep copy: You can encapsulate a copy () method.
Access array:
1. Find element: IndexOf () lastIndexOf ()
The indexOf () method returns the location of the first occurrence of the specified value in a string object. The lookup starts from the FromIndex position and returns 1 if it does not exist.
Str.indexof (searchvalue[, FromIndex])
Searchvalue represents the value being looked up.
FromIndex "Optional" represents the position in the string in which the method was called to begin the lookup. can be any integer. The default value is 0.
- FromIndex < 0, finds the entire string.
- FromIndex >= Str.length, the method returns 1, but when the string being looked up is an empty string, this returns STR.LENGTH.
/* * Index from left to right. The first character index is 0, and the last character index is stringname.length-1. * * "Hello World". IndexOf ("Hello"); Returns 0 "Hello World Hello". IndexOf ("Hello"); Returns 0 because it is returning the first occurrence of the position "Hello World". IndexOf ("World", 0); Returns 6 "Hello World". IndexOf ("World", 999); Returns -1 "Hello World". IndexOf ("", "ten); Returns "Hello World". IndexOf ("", 999); Returns 11/* * IndexOf method is case sensitive. For example, the following expression returns-1: */"Hello World". IndexOf ("Hello"); returns-1/* * Detects if there is a string */"Hello World". IndexOf ("Hello")!==-1; True "Hello World". IndexOf ("hel")!==-1; False
2. String representation of an array: converting an array to a string: Join () toString ()
The Join () method joins all elements in the array into a single string. (If the element is undefined or null, it is converted to an empty string.) )
str = Arr.join ([separator = ', '])
Separator "optional", specifying the delimiter to concatenate each array element. The delimiter will be converted to a string type;
- When Seprator is omitted, the default is a comma.
- When Seprator is an empty string, all elements in the array are directly connected.
/* * Use four different separators to concatenate array elements. * First created an array of arr, containing three elements, and then connecting all the array elements with four different separators. * First is the default delimiter comma, then a comma plus a space, followed by a plus and minus a space, and finally an empty string. */var arr = [' Apple ', ' Banner ', ' Orange '];var eg1 = Arr.join (); The value of EG1 changes to "Apple,banner,orange" var eg2 = Arr.join (', '); The EG2 value changes to "Apple, Banner, Orange" var eg3 = arr.join (' + '); The value of eg3 changes to "Apple + Banner + Orange" var eg4 = Arr.join ("); The value of EG4 changes to "Applebannerorange"
The toString () method returns a string representing the source code of the current function, that is, converting a value to a string.
Function.tostring ()
The function object overrides the Object.prototype.toString method inherited from object, including the function keyword, the formal parameter list, the curly braces, and the contents of the body.
The ToString method of a function is typically called automatically when a function needs to be converted to a string.
Seeing ToString () Here, I remember the implicit invocation of ToString () and valueof (). In a less rigorous sense, valueof () is implicitly called when calculations are required. ToString () is called when you need to display data or results in a string environment. Interested students can Google a bit.
3. Create a new array from an existing array:
The Concat () method merges multiple existing arrays, creating a new array
The splice () method intercepts a subset of an array to create a new array
The concat () method merges an incoming array or non-array value with the original array, forming a new array and returning it.
var New_array = Old_array.concat (value1[, value2[, ... [, Valuen]])
Valuen an array or non-array value that needs to be merged with the original array.
The Concat method creates a new array, does not modify the values of the individual arrays in the objects and parameters that call it, but copies each of their elements into a new array of combinations. There are two ways to copy:
- Object reference (non-object direct): The copied object reference is placed in a new set of arrays, both the original array and the new array refer to the same actual object, and when the actual object is modified, two arrays are modified.
- Strings and Numbers: Copies the values of strings and numbers into the new array.
The Concat method joins one or more arrays (values) without altering the original array/value.
/* * Connect two arrays, two arrays into a new array: */var arr1 = ["A", "B", "C"];var arr2 = [1, 2, 3];console.log (Arr1.concat (ARR2)); ["A", "B", "C", 1, 2, 3]/* * Three arrays merged into a new array */var num1 = [1, 2, 3];var num2 = [4, 5, 6];var num3 = [7, 8, 9];console.log ( Num1.concat (num2, num3)); [1, 2, 3, 4, 5, 6, 7, 8, 9]/* * Merges non-array values into an array, multiple arrays and multiple non-array values are combined into a new array */var Myarr = [' A ', ' B ', ' C '];console.log (Myarr.concat ( 1, [2, 3])); ["A", "B", "C", 1, 2, 3]
Of course, in addition to the above, the Concat method, ES6 and ES7 have support, interested students themselves Google
The Splice () method modifies the contents of an array by replacing the old element with a new element.
Array.splice (Start, deletecount[, item1[, item2[, ...])
Start? The location to begin modifying from the array.
- Beyond the length of the array, add from the end of the array;
- A negative value that represents the first digit from the bottom of the array.
An deletecount integer that represents the number of array elements to remove.
- The DeleteCount is 0 and does not remove the element. Indicates that at least one new element should be added.
- DeleteCount is greater than the total number of elements after start, the element after start is removed (including the start bit).
Itemn the element to be added into the array. When not specified, splice () deletes only the array elements.
Note that splice () is different from slice (), and the Splice () method modifies the array directly.
var num = ["One", "tow", "three", "four"];//remove 0 elements from the 2nd bit, insert "insert", equivalent to the added method Num.splice (2, 0, "Insert"); ["One", "tow", "Insert", "three", "four"]//delete 1 elements from 3rd bit Num.splice (3, 1); ["One", "tow", "Insert", "four"]
Variable functions:
1. Add elements to an array: the push () method adds the element to the end, Unshift () adds the element to the beginning
The push () method adds one or more elements to the end of the array and returns the new length of the array (the Length property value).
Arr.push (element1, ..., ELEMENTN)
var arr = ["A", "B"];arr.push ("C", "D"); Console.log (arr); ["A", "B", "C", "D"]
The unshift () method adds one or more elements at the beginning of the array and returns the new length value of the array.
Arr.unshift (element1, ..., ELEMENTN)
var arr = [1, 2];arr.unshift (0); [0, 1, 2]arr.unshift ( -2,-1); [-2,-1, 0, 1, 2]arr.unshift ([-3]); [[-3],-2,-1, 0, 1, 2]
2. Remove an element from an array: the POP () method deletes the element at the end of the array, and the Shift () method deletes the first element of the array
The pop () method deletes the last element in an array and returns the element.
Array.pop ()
var arr = ["A", "B", "C"];console.log (Arr.pop ()); deleted the last C
The shift () method deletes the first element of the array and returns the element. The method changes the length of the array.
Arr.shift ()
If the value of the length property is 0 (length 0), undefined is returned.
var arr = ["A", "B", "C"];console.log (Arr.shift ()); deleted the first A
3. To add and remove elements from an array's middle position: splice ()
It's been mentioned above.
4. Array Sort: Positive order (dictionary order): sort (), reverse; reverse ()
The sort () method sorts the elements of the array in situ and returns the arrays. The default is sorted by the Unicode code point of the string.
Arr.sort ([comparefunction])
Comparefunction "Optional" is used to specify functions that are arranged in some order.
/** * Comparefunction omitted, the elements are converted to strings and sorted in the order of the universal code points. */var words = [' one ', ' three ', ' Four '];console.log (Words.sort ()); [' Four ', ' one ', ' three ']var num = [3], 21];console.log (Num.sort ()); Sorted by Dictionary: [10, 100, 21, 3]/** * When Comparefunction is indicated, the array is sorted by the return value of the call to the function. Notes A and B are two elements to be compared * when comparefunction (A, B) < 0, A is arranged before B; * When Comparefunction (A, B) = 0, the relative position of A and b are unchanged; * When Comparefunction (A, B) > 0, B is aligned to A; * When Comparefunction (A, B) must always return the same comparison result for the same input, otherwise the result of the sort will be indeterminate. */var nums = [4, 2, 5, 1, 3];nums.sort (function (A, b) {return b-a;}); Console.log (nums);//[5, 4, 3, 2, 1]/** * below creates four arrays * shows the original array, sorts the arrays, compares the numeric arrays with the results without specifying the comparefunction case. */var EG1 = ["Cat", "dog", "bear"];var EG2 = ["" "," 9 "," Max "];var eg3 = [1, 5, 200];var eg4 = [" 80 "," 9 "," 700 ", 40, 1, 5, 200];//when the comparison function is used, the numeric array is sorted by the number size. function Compare (A, b) {return a-A;} Console.log (' EG1: ', Eg1.join ()); Console.log (' Sorted: ', Eg1.sort ()); Console.log (' EG2: ', Eg2.join ()); Console.log (' No comparison function is used: ', Eg2.sort ()); Console.log (' Use comparison function: ', Eg2.sort (Compare)); Console.log (' Eg3: ', Eg3.join ()); Console.log (' No comparison function used: ', Eg3.sort ()); Console.log (' Use comparison function: ', Eg3.sort (Compare)); Console.log (' Eg4: ', Eg4.join ()); Console.log (' No comparison function used: ', Eg4.sort ()); Console.log (' Use comparison function: ', Eg4.sort (compare));
Mapping Optimizations:
When there are more elements, the comparefunction may have a high load, using map-assisted sorting. The actual value of the comparison of each element in the array is first taken out, sorted before the array is restored.
Iterators:
Each element of an array uses a function that can return a value, a set of values, or a new array
- An iterative method that does not generate a new array; ForEach () every () some () reduce ()
- An iterative method for generating a new array: Map () and filter ().
The map () method returns a new array that consists of a return value from each element in the original array that invokes a specified method.
Array.map (callback[, Thisarg])
The callback function returns 3 parameters
- CurrentValue The first argument, the element that is currently passed in the array.
- Index the second argument, in the array, of the element that is currently being passed.
- The third parameter of array, which calls the array of the map method, generally refers to the original array itself.
Thisarg the "optional" callback function when this object is pointed, omitted or assigned to null or undefined, this points to the global object.
The map method invokes the callback function sequentially for each element in the original array. Callback the return value after each execution is combined to form a new array. The callback function is only called on the indexed index, and those indexes that have never been assigned a value or deleted by using Delete are not called.
/* * Find the square root of each element in the array */var numbers = [1, 4, 9];numbers.map (MATH.SQRT); [1, 2, 3]/* * Generally, the callback function in the map method accepts only one parameter, which is the array element itself that is being traversed. * But in some cases more than one parameter is passed in. This makes it easy for us to make mistakes. */["1", "2", "3"].map (parseint); [1, NaN, nan]//maybe a lot of people start thinking back [1, 2, 3], the reason they went to Google.
The filter () method tests all elements with the specified function and creates a new array that contains all the elements passed through the test.
Arr.filter (callback[, Thisarg])
Callback the function used to test each element of an array.
Pass in three parameters:
- The value of the element
- Index of the element
- The array being traversed
Thisarg "Optional" the value to use for this when executing callback.
/* * Filter greater than a specified value */function IsBig (Element) { return element <= 100;} [5, 8, 44].filter (IsBig); [12, 5, 8, 44]
Two-dimensional and multidimensional arrays:
1. Creating a two-dimensional array
JavaScript supports only one-dimensional arrays, but you can create multidimensional arrays by saving array elements in an array. A two-dimensional array resembles a data table consisting of rows and columns. Create a two-dimensional array in JavaScript, create an array first, and then let each element of the array be an array.
This expands the array object by adding a new method that sets the number of rows, columns, and initial values of the array. Here is the definition of this method (referring to javascript:the good Parts (O ' Reilly) a piece of code):
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; }
2. Processing mode I: Using embedded for loop
Object array:
Arrays contain objects In addition to basic data type elements (numbers, strings), and the methods and properties of arrays still apply to objects. In an object, you can use an array to store complex data.
Little Practice
1. Filter the maximum and minimum values in an array
*/* Adhering to the idea of packaging methods as much as possible, * using a quick sort to derive a positive sequence of arrays; * The minimum is the leftmost number and the maximum value is the rightmost number. */function QuickSort (arr, left, right) {function swap (arr, A, b) {var temp = Arr[a]; Arr[a] = arr[b]; ARR[B] = temp; }//In-situ partitioning algorithm function partition (arr, left, right) {var pivot = Arr[right]; var storeindex = left; for (var i = left; I < right; i++) {if (Arr[i] < pivot) {swap (arr, storeindex, i); storeindex++; }} swap (arr, right, storeindex); return storeindex; } function sort (arr, left, right) {if (Left > right) return; var storeindex = partition (arr, left, right); Sort (arr, left, storeIndex-1); Sort (arr, Storeindex + 1, right); } sort (arr, 0, arr.length-1); return arr;} var arry = [1, 2, 8];quicksort (Arry); Console.log (QuickSort (Arry)); [1, 2, 8,]var max = Arry[arry.length-1];var min = arry[0];console.log (max); 20Console.log (min); 1
2. For an array, specify an element, delete it and return the new array
/* * here is a simple splice () method */function deletes (arr, target) {for (var i = 0; i < arr.length; i++) { if (Arr[i] = = target) { Arr.splice (i, 1) } } return arr; var arr = [' as ', ' 0uou ', '];console.log ' (Deletes (arr.)); [' as ', ' 0uou ']//I deleted the number 88, it put my string ' 88 ' also deleted. Here is the implicit invocation of the ToString method as mentioned above//the workaround is to add a type judgment, where I no longer provide the code.
3. Determine if the same element exists in an array
/* * I offer a reference here, of course, a better approach is to use a hash table */function Issame (arr) { var store = arr; for (var i = 0, i < arr.length; i++) {for (var k = i + 1; k < store.length; k++) { if (store[k] = = Arr[i]) { return True } } } return False}var a = Issame ([1, 7, 7, 9]); Console.log (a); True
4. Array de-weight (optimal solution)
function Unique (arr) { var hash = {}, result = [], type = ', item; for (var i = 0; i < arr.length; i++) { item = Arr[i];
Judgment type = Object.prototype.toString.apply (item); if (!hash[item + type]) { Hash[item + type] = true; Result.push (item); } } return result;} var Testarr = [1, ' null ', NULL, null, undefined, undefined, 2, 1, ' 2 ', 3, Nan, Nan, {"Name": 1}, {"Name": 2}, {"Name": 1}] ; Console.log (Unique (Testarr)); [1, ' null ', null, undefined, 2, ' 2 ', 3, NaN, {name:1}]
Data structure and algorithm JavaScript description