Javascript Array Method)

Source: Internet
Author: User

In JavaScript, Arrays can be created using an Array constructor or [] for quick creation. This is the preferred method. An array is a prototype inherited from an Object and has no special return value for typeof. Only 'object' is returned '. Run [] instanceof Array and it will return true. Although the result is like this, there are also complex class Array objects, such as strings or arguments objects, but the arguments object is not an Array instance, but it has the length attribute, and its value can be indexed, so it can be traversed as an array. In this article, I will introduce some methods of the array prototype and explore the purpose of each method: Use. forEach is used for traversal. some and. every. join and. concat is used in combination. pop ,. push ,. shift, and. unshift for Stack operations and queue usage. map ing model usage. filter is used for query. use sort for sorting. reduce ,. reduceRight is used for computing. server Load balancer. usage of splice. indexOf to find in operator introduction. use of reverse. forEach to traverse ======== this is one of the simplest methods for native Javascript arrays, but he does not support IE6 ~ 8. ForEach executes a callback function when traversing each element in the array and passes three parameters. Value the current array element index the position of the current element in the array references the array. In addition, we can also pass an optional parameter as the context (this) for each function call ), take the following example: ['_', 't', 'A', 'n', 'I, f',']. forEach (function (value, index, array) {this. push (String. fromCharCode (value. charCodeAt () + index + 2)}, out = []) out. join ('') // <-'awess' is used here. join, which we haven't mentioned yet, but we will introduce it later. In this example, it can connect different elements in the array to achieve the effect similar to String concatenation. Out [0] + ''+ out [1] +'' + out [2] + ''+ out [n]. we cannot abort the forEach loop or throw an exception. In these scenarios, we can choose to use other available methods. Use. some and. every to assert ===== if you have used. net enumerables, maybe you are familiar. any (x => x. isAwesome) and. all (x => x. isAwesome ). these methods and. forEach is very similar. They also pass value, index, and array to the callback function. You can also pass two optional parameters to the callback function as the context. MDN is described in this way. some :". some methods can execute a callback function when traversing every element of the array until the callback function returns true. If this element is found ,. some returns true immediately. Otherwise. some returns false. the callback function only calls the index of non-null elements in the array and does not call the deleted or unassigned value. "Copy code max =-Infinitysatisfied = [10, 12, 10, 8, 5, 23]. some (function (value, index, array) {if (value> max) max = value return value <10}) console. log (max) // <-12 satisfied // <-true: the callback function of the copied code stops execution when the value that meets the condition is <10 .. The same applies to every, but his short circuit occurs when the callback function returns false. Use. join and. concat to merge =====. the join method is usually confused with the. concat method .. Join creates a string that uses delimiters to link elements in an array. If a separator is not provided, the separator is used by default .. Concat creates a new array through its source number group.. Concat can input multiple parameters: array. concat (val, val2, val3, valn ). concat can return a new array. concat () If no parameter is input, a new shallow copy array is returned. A shallow copy means that the copy can store object references of the source array. For example, copy the code var a = {foo: 'bar'} var B = [1, 2, 3, a] var c = B. concat () console. log (B = c) // <-false B [3] = a & c [3] = a // <-true to copy the code. pop ,. push ,. shift, and. unshift to operate the stack and queue ===now everyone knows you can use. the push method adds elements to the array, but do you know. push can input multiple parameters, and add multiple parameters to the end of the array at a time. For example, []. push ('A', 'B', 'C', 'D', 'z'). The pop method is the opposite of the. push method. It will return the last element in the array and delete the element from the array at the same time. If the array is empty, void. (undefined) is returned ). Using. push and. pop, I can easily create a LIFO (last in first out) stack. Copy the code function Stack () {this. _ stack = []} Stack. prototype. next = function () {return this. _ stack. pop ()} Stack. prototype. add = function () {return this. _ stack. push. apply (this. _ stack, arguments)} stack = new Stack () stack. add (1, 2, 3) stack. next () // <-3 copy the code. Otherwise, you can use it. unshift and. shift creates a FIFO (fist in first out) queue. Copy the code function Queue () {this. _ queue = []} Queue. prototype. next = function () {return this. _ queue. shift ()} Queue. prototype. add = function () {return this. _ queue. unshift. apply (this. _ queue, arguments)} queue = new Queue () queue. add (1, 2, 3) queue. next () // <-1 copy the code to use. shift (or. pop) can easily traverse the array. Copy the code list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] while (item = list. shift () {console. log (item)} list // <-[] use to copy the code. map ing model ==========. when traversing each element in the array, map executes a callback function and returns a new array. The callback function only performs the element index of the array and does not perform the deleted or no element index. The Array. prototype. map method is similar to. forEach,. some and. every:. map (fn (value, index, array), thisArgument ). Copy the code values = [void 0, null, false, ''] values [7] = void 0 result = values. map (function (value, index, array) {console. log (value) return value}) // <-[undefined, null, false, '', undefined × 3, undefined] indicates copying the undefined × 3 code. map is not executed on a deleted or undefined array element, but they are retained on the result array. Ing is very useful for Array conversion. See the following example: copy the code // casting [1, '2', '30', '9']. map (function (value) {return parseInt (value, 10)}) // 1, 2, 30, 9 [97,119,101,115,111,109,101]. map (String. fromCharCode ). join ('') // <-'awessome '// a commonly used pattern is mapping to new objectsitems. map (function (item) {return {id: item. id, name: computeName (item)}) used to copy the code. filter to query ======. when the filter traverses each element in the array, it executes a callback function. When the callback function returns true, it will save the current element, Returns a new array. The callback function only performs the element index of the array and does not perform the deleted or no element index. Elements that are not passed to the callback function will be ignored and will not appear in the new array. Copy the Code [void 0, null, false, '', 1]. filter (function (value) {return value}) // <-[1] [void 0, null, false, '', 1]. filter (function (value) {return! Value}) // <-[void 0, null, false, ''] use to copy the code. sort performs sorting ======== if a callback function is not provided, the elements are converted to characters and sorted in the dictionary order. For example, in the dictionary, "80" is before "9", but 9 is before 80 if it is sorted by number. Like most sorting functions, Array. prototype. sort (fn (a, B) can compare two elements. And return values in the following three cases. If a should appear before B, the return value is less than 0. If a and B are equal, 0 is returned. If a should appear after B, the return value is greater than 0. Copy the Code [9, 80,]. sort () // <-[10, 3, 5, 6, 80, 9] [9, 80, 3, 10, 5, 6]. sort (function (a, B) {return a-B}) // <-[3, 5, 6, 9, 10, 80] copy the code to use. reduce ,. reduceRight to calculate ========= both methods have the same features :. reduce (callback (previusvalue, currentValue, index, array), initialValue ). previusvalue is returned when each callback function is executed. During initialization, initialValue will be passed in the callback function. currentValue contains the current element, and index indicates the position of the element in the array. Array is an array reference. A typical. reduce example is an addition function. Copy the code Array. prototype. sum = function () {return this. reduce (function (partial, value) {console. log (partial, ",", value) return partial + value}, 0)}; [3, 4, 5, 6, 10]. sum () // <-28 copy the Code. If we want to merge some strings, we may use it. join method. However, in the following example, The. join method cannot meet our requirements unless these objects have the valueOf or toString attribute. However, we can use the. reduce method to easily merge objects into strings. Copy the code function concat (input) {return input. reduce (function (partial, value) {if (partial) {partial + = ','} return partial + value. name}, '')} concat ([{name: 'George '}, {name: 'Sam'}, {name: 'pear '}]) to copy the code. slice to copy ====== Array. prototype. slice can be used to convert array-like objects into real arrays. and. similar to concat, you can pass a parameter. the slice Method to copy the source array .. The slice method can pass in two parameters: one is the start position and the other is the end position. Array. prototype. slice can also convert the class Array into an Array. Array. prototype. slice. call ({0: 'A', 1: 'B', length: 2}) // <-['A', 'B. concat cannot achieve this goal, because it will put the class array into a real array. Array. prototype. concat. call ({0: 'A', 1: 'B', length: 2}) // <-[{0: 'A', 1: 'B', length: 2}] In addition, we can also convert the class array to a real array, and remove the first several elements of the array. Copy the code function format (text, bold) {if (bold) {text = '<B>' + text + '</B>'} var values = Array. prototype. slice. call (arguments, 2) values. forEach (function (value) {text = text. replace ('% s', value)}) return text} format ('some % sthing % s % s', true, 'some', 'other', 'things ') // <-<B> somesomethingother things </B> copy the code. splice purpose ====. splice is also a common array method. You can use. splice to delete elements, insert new elements, and call. splice to delete elements at the same position. Note that this method will change the source array. Copy the code var source = [, 8, 8, 8, 9, 10, 11, 12, 13] var spliced = source. splice (3, 4, 4, 5, 6, 7) console. log (source) // <-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] spliced // <-[8, 8, 8, 8] copy the code. if you pay attention to it, it will return the deleted element. Copy the code var source = [, 8, 8, 8, 9, 10, 11, 12, 13] var spliced = source. splice (9) spliced. forEach (function (value) {console. log ('removed', value)}) // <-removed 10 // <-removed 11 // <-removed 12 // <-removed 13 console. log (source) // <-[1, 2, 3, 8, 8, 8, 8, 8, 9] use the copy code. indexOf to find ========= by using. indexOf method, we can find the position of the element in the array. If not,-1 is returned. If you want to search, I usually write and compare a = 'A' | a = 'B' | a = 'C', but in this scenario, you can ['A', 'B', 'C']. indexOf ()! =-1. Note that if you are looking for objects in an array, you must provide the same object reference. The second parameter indicates the position in the array to start searching. Copy the code var a = {foo: 'bar'} var B = [a, 2] console. log (B. indexOf (1) // <--1 console. log (B. indexOf ({foo: 'bar'}) // <--1 console. log (B. indexOf (a) // <-0 console. log (B. indexOf (a, 1) // <--1 B. indexOf (2, 1) // <-1 copy the Code. If you want to search in reverse order, you can use. lastIndexOf. In operator introduction ==========. indexOf and in operators are very confusing. Copy the code var a = [1, 2, 5] 1 in a // <-true, but because of the 2! 5 in a // <-false copying the code here, the in operator is used to check the key of an object, rather than finding the position of an element in the array. Of course, this is faster than. indexOf. Var a = [3, 7, 6] 1 in a = !! A [1] // <-The truein operator converts the passed value to a Boolean value .!! The expression can implicitly convert a value to a Boolean value. About. reverse ======== this method can reverse the element position in the array. Var a = [1, 1, 7, 8]. reverse () // [8, 7, 1, 1] Here, instead of returning a copy, it directly modifies the array itself.

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.