JavaScript native Array function Use example

Source: Internet
Author: User
Tags foreach arrays pear shallow copy


In JavaScript, creating an array can use the array constructor, or use the array direct amount [], which is the preferred method. The array object inherits from the Object.prototype, and the array performs the typeof operator to return object instead of array. However, [] instanceof array also returns TRUE. That is, the implementation of the class array object is more complex, such as the strings object, the arguments object, the arguments object is not an array instance, but has the length property, and can be indexed to the value, so can be like an array of loop operation.
In this article, I'll review some of the methods of array prototypes and explore the use of these methods.

Loop:. ForEach
Judgment:. Some and. every
Distinguish. Join and. Concat
Implementation of stacks and queues:. Pop,. Push,. Shift, and. Unshift
Model mappings:. Map
Query:. Filter
Sort:. Sort
Calculated:. Reduce and. Reduceright
Copy:. Slice
Powerful. Splice
Find:. indexOf
Operator: in
Come near. Reverse
Array

Loop:. ForEach

This is the simplest method in JavaScript, but IE7 and IE8 do not support this method.

. ForEach has a callback function as an argument, and each array element calls it when it traverses the array, and the callback function accepts three parameters:

Value: Current element

Index: Indexes of the current element

Array: Arrays to traverse

In addition, you can pass the optional second argument as the context for each function call (this).

[' _ ', ' t ', ' a ', ' n ', ' I ', ' f ', '] '].foreach (function (value, index, array) {
This.push (String.fromCharCode (value.charcodeat () + index + 2))
}, out = [])
Out.join (")"
<-' Awesome '
<div class= "Md-section-divider" ></div>

The following article mentions. Join, in this example, is used to stitch the different elements in an array, and the effect is similar to out[0] + ' + out[1] + ' + out[2] + ' + out[n '.
You cannot break the. Foreach loop, and it is unwise to throw an exception. Fortunately, we have another way to interrupt the operation.

Judgment:. Some and. every

If you've ever used. NET, the two methods and the. Any (x => x.isawesome),. All (x => x.isawesome) is similar.
Similar to the parameters of the. foreach, a callback function containing the Value,index, and array three parameters is required, and an optional second context parameter is also available. MDN's description of. Some is as follows:

Some will execute the callback function once for each element in the array until the callback function returns TRUE. If the target element is found, some returns true immediately, otherwise some returns false. The callback function executes only on an array index that has a specified value, and it is not invoked on elements that have been deleted or that do not specify a value.
max =-infinity
satisfied = [8, 5, 23].some (function (value, index, array) {
if (Value > Max) max = value
return value < 10
})
Console.log (max)
<-12
Satisfied
<-true
<div class= "Md-section-divider" ></div>

Note that when the callback function's value < 10 o'clock, the interrupt function loop ... every's operation is similar to. Some, but the callback function returns false instead of true.

Distinguish. Join and. Concat
. Join and. Concat are often confused. Join (separator) joins the array element in separator as a delimiter, and returns a string that, if separator is not provided, uses the default,。. concat creates a new array. As a shallow copy of the source array.

Concat Common usage: Array.concat (val, Val2, Val3, Valn)
. Concat returns a new array
Array.concat () returns a shallow copy of the source array, without parameters.
A shallow copy means that the new array retains the same object reference as the original array, which is usually a good thing. For example:
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
Implementation of stacks and queues:. Pop,. Push,. Shift and. Unshift

Everyone knows. Push can add elements at the end of an array, but do you know that you can add multiple elements at once by using [].push (' A ', ' B ', ' C ', ' d ', ' Z ')?

The. Pop method is the reverse operation of the. Push, which returns the element at the end of the array being deleted. If the array is empty, void 0 (undefined) is returned, using. Pop and. Push to create a LIFO 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 (1,2,3)
Stack.next ()
<-3

Instead, you can use. Shift and. Unshift to create a FIFO (in-in-out) queue.

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
A Using. Shift (or. POPs) is a easy way to loop through a set of array elements, while draining the "array in" process.
List = [1,2,3,4,5,6,7,8,9,10]
while (item = List.shift ()) {
Console.log (item)
}
List
<-[]

Model mappings:. Map

The. Map provides a callback method for each element in the array and returns a new array with the result of the invocation. The callback function executes only on an array index that has a specified value, and it is not invoked on elements that have been deleted or that do not specify a value.

Array.prototype.map and the above mentioned. ForEach,. Some and. Every have the same parameter format:. Map (FN (value, index, array), thisargument)

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

Undefinedx3 a good explanation. Map will not be called for deleted or unspecified elements, but will still be included in the result array.. map is useful when creating or changing arrays, see the following example:

Casting
[1, ' 2 ', ', ', ' 9 '].map (function (value) {
return parseint (value, 10)
})
1, 2, 30, 9.
[119, 109, 101].map (String.fromCharCode). Join (")
<-' Awesome '
A commonly used pattern are mapping to new objects
Items.map (function (item) {
return {
Id:item.id,
Name:computename (item)
}
})

Query:. Filter

Filter executes a callback function for each array element and returns a new array of elements that return true by the callback function. The callback function is invoked only for an array item that already has a specified value.
Common usage:. Filter (FN (value, index, array), thisargument), similar to the LINQ expression in C # and the WHERE statement in SQL,. Filter returns only the element that returns a true value in the callback function.

[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, ']

Sort:. Sort (comparefunction)

If Comparefunction is not provided, the elements are converted to strings and sorted by dictionary. For example, "80″ is ranked" before 9″, not after.

Like most sort functions, Array.prototype.sort (FN (a,b)) requires a callback function that contains two test parameters, and the return value is as follows:

A The return value is less than 0 before B
A and B equals the return value is 0
A after b The return value is less than 0
[9,80,3,10,5,6].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]

Calculated:. Reduce and. Reduceright

These two functions are more difficult to understand. Reduce traverses the array from left to right, while. Reduceright traverses the array from right to left, which is typically used:. Reduce (callback Previousvalue,currentvalue, index, Array), InitialValue).

Previousvalue is the return value of the last call to the callback function, InitialValue is its initial value, the CurrentValue is the current element value, index is the current element index, and array is the one that calls. Reduce.

A typical use case, using the SUM function of. Reduce.

Array.prototype.sum = function () {
Return This.reduce (function (partial, value) {
return partial + value
}, 0)
};
[3,4,5,6,10].sum ()
<-28
<div class= "Md-section-divider" ></div>
If you want to concatenate an array into a string, you can use the. Join implementation. However, if the array value is an object,. Join does not return a value as we expect unless the object has a reasonable valueof or ToString method, in which case you can use the. Reduce implementation:

function concat (input) {
Return Input.reduce (function (partial, value) {
if (partial) {
Partial + = ', '
}
return partial + value
}, '')
}
Concat ([
{name: ' George '},
{name: ' Sam '},
{name: ' Pear '}
])
<-' George, Sam, Pear '
<div class= "Md-section-divider" ></div>

Copy:. Slice

Like. Concat, calling the. Slice () method without parameters returns a shallow copy of the source array ... slice has two parameters: one is the start position and one end position.

Array.prototype.slice can be used to convert a class array object to a true array.

Array.prototype.slice.call ({0: ' A ', 1: ' B ', length:2})
<-[' A ', ' B ']
This does not apply to. concat because it uses arrays to wrap arrays of objects.

Array.prototype.concat.call ({0: ' A ', 1: ' B ', length:2})
<-[{0: ' A ', 1: ' B ', length:2}]
Also, another common use of. Slice is to remove some elements from a list of parameters, which converts the class array object to a true array.

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>

Powerful. Splice

Splice is my favorite native array function that only needs to be invoked once, allowing you to delete elements, insert new elements, and simultaneously delete and insert operations. It should be noted that unlike '. Concat and. Slice, this function changes 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, 10, 11, 12, 13]
Spliced
<-[8, 8, 8, 8]

As you can see,. Splice returns the deleted element. This is handy if you want to traverse an array that has been deleted.

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 13
Console.log (source)
<-[1, 2, 3, 8, 8, 8, 8, 8, 9]
Find:. indexOf
Use. indexOf to find the position of an element in an array, and return 1 without a matching element. I often use. indexof is when I have a comparison, for example: a = = = ' A ' | | A = = = ' B ' | | A = = = = ' C ', or only two comparisons, at this time, you can use. indexof:[' A ', ' B ', ' C '].indexof (a)!==-1.
Note that, if the references provided are the same,. IndexOf can also find objects. The Second optional parameter specifies where to start the lookup.

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
If you want to search backwards, you can use the. LastIndexOf.

Operator: in

The mistakes that beginners make in an interview are confusing. IndexOf and in operators:

var a = [1, 2, 5]
1 in a
<-true, but because of the 2!
5 in a
<-false
The problem is that the in operator retrieves the key of the object rather than the value. Of course, this is much faster than the indexof.

var a = [3, 7, 6]
1 in a = = =!! A[1]
<-true

Come near. Reverse
This method inverts the elements in the array.

var a = [1, 1, 7, 8]
A.reverse ()
[8, 7, 1, 1]
. reverse modifies the array itself.

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.