Common methods of arrays in JavaScript

Source: Internet
Author: User
Tags shallow copy

In JavaScript, arrays can be created using the array constructor, or created quickly using [], which is also the preferred method. The array is a prototype inherited from object, and he has no special return value for typeof, he only returns ' object '.

Run [] instanceof array He will return to ture. Although the result is this, there are also complex class array objects, such as strings or arguments objects, but the arguments object is not an instance of array, but he has the length property, and his value can be indexed, so he can be traversed like an array.

In this article, I will describe some of the methods of array prototyping and explore the purpose of each method:
Use. ForEach to do the traversal
Use. Some and. Every to assert
Use the. Join and. Concat to merge
Use. Pop,. Push,. Shift, and. Unshift to manipulate stacks and queues
Using the. Map Mapping model
Use. filter to make queries
Use the. Sort to do the sorting
Use. Reduce,. Reduceright to calculate
Use. Slice to replicate
Use of the. Splice
Use the. IndexOf to find
In operator introduction
Use of the. Reverse

Use. foreach to traverse
======
This is one of the simplest ways of native javascript arrays, but he does not support ie6~8.

ForEach executes a callback function once each element in the array is traversed and passes three parameters.
Value the current array element
Index the position of the current element in the array
Array references to arrays

In addition, we can pass an optional parameter as the context for each function call (this), see the following example:

[' _ ', ' t ', ' a ', ' n ', ' I ', ' f ', '] '].foreach (function (value, index, array) {    This.push (String.fromCharCode ( Value.charcodeat () + index + 2)}, out = []) out.join (")//<-' awesome '


This is used here. Join, which we have not yet mentioned, but we will introduce later, in this example, he can connect the different elements in the array, can achieve similar string concatenation effect. Out[0] + ' + out[1] + ' + out[2] + ' + out[n].

We cannot abort the Foreach loop and throw an exception, and in these scenarios we can choose to use other available methods.


Use. Some and. Every to assert
=====

If you've ever used it. Net of Enumerables, perhaps you are familiar with. Any (x = X.isawesome) and. All (x = X.isawesome).
These methods are very similar to. foreach, and they also pass value, index, and array to the callback function, and you can also give him two optional arguments as the context of the callback function. MDN is described in this way. Some:

The. Some method can execute a callback function while iterating through each element in the array until the callback function returns True, and if the element is found,. Some immediately returns true. otherwise. Some will return false. The callback function is called only for an index of the non-empty element of the group, and does not invoke a value that has been deleted or has never been assigned.

max =-infinitysatisfied = [Ten, 8, 5, +/-(function (value, index, array) {    if (value > Max) max = Valu e    return value < ten} console.log (max)//<-12satisfied//<-True

The callback function stops executing when the condition value < 10 o'clock is met: Every is the same, but his short circuit occurs when the callback function returns FALSE.


Use the. Join and. Concat to merge
=====
The. Join method is often confused with the. Concat method: Join is a string that creates a delimiter to link elements in an array, and if you do not provide a delimiter, he defaults to the comma-acting delimiter: Concat creates a new array from his source array.

. Concat can pass in multiple parameters: Array.concat (Val, Val2, Val3, Valn)
The. Concat is a new array that can be returned
Array.concat () If you do not pass in the parameter, a new shallow copy array will be returned.

A shallow copy means that a copy can hold an object reference to the source array. For example:

var a = {foo: ' bar '}var b = [1, 2, 3, A]var C = B.concat () console.log (b = = = c)//<-falseb[3] = = = a && c[3] = = = a//<-true


Use. Pop,. Push,. Shift, and. Unshift to manipulate stacks and queues
===
Now we all know that you can add elements to and from the array through the. Push method, but do you know. Push can pass in multiple parameters, adding multiple parameters to the array at once. such as: [].push (' A ', ' B ', ' C ', ' d ', ' Z ')

The. Pop method and the. Push method are just the opposite. He will return the last element in the array and remove the element from the array at the same time. If the array is empty, void is returned. (undefined). With. Push and. Pop, I can easily create a LIFO (last on first out) stack.

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 (Stack.next)//<-3


Instead, I can create a queue of FIFO (fist in First out) by using. Unshift and. Shift.

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 (Queue.next)//<-1

Use. Shift (or. Pop) to easily repeat the group.

List = [1,2,3,4,5,6,7,8,9,10]while (item = List.shift ()) {    Console.log (item)}list//<-[]


Using the. Map Mapping model
=========
. map executes a callback function once each element in the array is traversed, and a new array is returned. The callback function executes only the element index of the array and does not execute on the index of the deleted or no element.

The Array.prototype.map method and. Foreach,.some and. Every have a similar place:. Map (FN (value, index, array), thisargument).

values = [void 0, NULL, FALSE, ']values[7] = void 0result = Values.map (function (value, index, array) {    Console.log (val UE)    return value}//<-[Undefined, null, false, ' ', undefinedx3, undefined]

The undefinedx3 means that. Map does not execute on a deleted or undefined array element, but they remain on the result array. Mapping is useful for converting an array. Look at the following example:

Casting[1, ' 2 ', ' A ', ' 9 '].map (function (value) {    return parseint (value, 10)})//1, 2, 30, 9[97, 119, 101, 115, 111 , 109, 101].map (String.fromCharCode). Join (')//<-' awesome '//a commonly used pattern is mapping to new OBJECTSITEMS.M AP (function (item) {    Return {        id:item.id,        name:computename (item)    }})


Use. filter to make queries
======

. Filter executes a callback function once each element in the array is traversed, and when the callback function returns True, he will save the current element and finally return a new array. The callback function executes only the element index of the array and does not execute on the index of the deleted or no element. Elements that are not passed to the callback function are simply ignored and will not appear in the new array.

[void 0, NULL, FALSE, ', 1].filter (function (value) {    return value})//<-[1][void 0, NULL, FALSE, ', 1].filter (f Unction (value) {    return!value})//<-[void 0, NULL, FALSE, ']


Use the. Sort to do the sorting
========

If you do not provide a callback function, the elements are sorted by converting to characters and then in the order in the dictionary. For example, in the dictionary "80" precedes "9", but if you sort by number, 9 is before 80.

Just like most sort functions, Array.prototype.sort (A, B) can compare two elements. and returns a value 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.

[9,80,3,10,5,6].sort ()//<-[3, 5, 6, 3, 9][9,80,3,10,5,6].sort (function (A, b) {return a-B    })//<-[, 5 , 6, 9, 10, 80]


Use. Reduce,. Reduceright to calculate
========
Both of these methods have the same characteristics:
. Reduce (Callback (Previousvalue, CurrentValue, Index, array), InitialValue).
When each callback function executes, the Previousvalue will be returned. At initialization time, InitialValue will be passed into the callback function, CurrentValue contains the current element, and index represents the position of the element in the array. Array is an array of references.
A classic. Reduce example is the addition function.

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


If we were to merge some strings, we might use the. Join method to achieve the goal. However, in the following example, the. Join method may not be able to reach our requirements unless these objects have a valueof or ToString property. But we can use the. Reduce method to easily implement merging each object as a string.

function concat (input) {    return input.reduce (function (partial, value) {        if (partial) {            partial + = ', '        }        return partial + value.name    }, ')} Concat ([    {name: ' George '},    {name: ' Sam '},    {name: ' Pear '}])

Note: The difference between reduce and reduceright is that reduce is traversed from left to right of the array, and reduceright is traversed from right to left of the array.


Use. Slice to replicate
======
Array.prototype.slice can used to convert array-like objects into real arrays.
Similar to. concat, you can copy the source array by not passing parameters to the. Slice method: 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 a class array to an array.

Array.prototype.slice.call ({0: ' A ', 1: ' B ', length:2})//<-[' A ', ' B ']

But with. Concat, this is not the purpose, because he 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 elements from the front of the array.

function format (text, bold) {    if (bold) {        text = ' <b> ' + text + ' </b> '    }    var values = ARRAY.P Rototype.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>


Use of the. Splice
====
. Splice is also a common array method. You can delete an element by using. Splice, insert a new element, and you can call it once. Splice in the same position to achieve the deletion, the target of the inserted element is not. It is important to note that this method will change the source array.

var Source = [1,2,3,8,8,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, ten, one, a, 13]spliced//<-[8, 8, 8, 8]

If you have noticed, he will return the deleted element.

var Source = [1,2,3,8,8,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 13console.log (sou RCE)//<-[1, 2, 3, 8, 8, 8, 8, 8, 9]


Use the. IndexOf to find
=========
By using the. IndexOf method, we can find the position of the element in the array. If it is not found, it will return-1. If you want to find, usually I will write the comparison a = = = ' A ' | | A = = = ' B ' | | A = = = ' C ', but in this scenario, you can [' A ', ' B ', ' C '].indexof (a)!==-1.

Note that if you are looking for an object in an array, you will provide the same object reference. The second parameter is the position in the array from which to start the search.

var a = {foo: ' bar '}var b = [A, 2]console.log (B.indexof (1))//<- -1console.log (B.indexof ({foo: ' Bar '})//<- -1c Onsole.log (B.indexof (a))//<-0console.log (B.indexof (A, 1))//<- -1b.indexof (2, 1)//<-1


If you want to reverse-order lookups, you can use. lastIndexOf.

In operator introduction
========
The. IndexOf and in operators are very easy to confuse.

var a = [1, 2, 5]1 in a//<-true, but because of the 2!5 in a//<-false

The problem here is that the in operator is used to check the key of an object, rather than finding the position of an element in an array. Of course it's faster than. IndexOf.

var a = [3, 7, 6]1 in a = = =!! a[1]//<-True

The In operator converts the value passed in to a Boolean value.!! An expression is the ability to implicitly convert a value to a Boolean value.

About. Reverse
=========
This method can reverse the position of an element in an array.

var a = [1, 1, 7, 8]a.reverse ()//[8, 7, 1, 1]

Instead of returning a copy, the array itself is modified directly.

Common methods of arrays in JavaScript

Related Article

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.