JavaScript Summary-Arrays

Source: Internet
Author: User
Tags prev

Array type

Each item of the ECMAScript array can hold any type of data.

There are two ways to create an array :

(1) using the array () constructor

var colors = new Array (20);

var colors = new Array ("Red", "Blue", "green");

(2) array literal notation

var colors = ["Red", "Blue", "green"];

Modify, add

var colors = ["Red", "Blue", "green"]

COLORS[2] = "BLACK"; Modify

COLORS[3] = "Brown"//New

Property

(1) Constructor:

Definition and usage

The constructor property returns a reference to the array function that created this object.

Grammar

Object.constructor

Instance

Example 1

In this example, we will show how to use the constructor property:

<script type= "Text/javascript" >
var test=new Array ();
if ( test.constructor==Array )
{
document.write ("This was an Array");
}
</script>

(2) Length: The number of items to save the array

Cases:

var colors = ["Red", "Blue", "green"];

alert (colors.length); 3

(3) The prototype property gives you the ability to add properties and methods to an object.

Grammar
Object.prototype.name=value
Instance

In this example, we will show how to use the prototype property to add properties to an object:

<script type= "Text/javascript" >
function Employee (Name,job,born)
{
    This.name=name;
    This.job=job;
    This.born=born;
}
VAR bill=new employee ("Bill Gates", "Engineer", 1985);
employee.prototype.salary=null;
bill.salary=20000;
document.write (bill.salary);
</script>

detecting arrays

(1) if (value instanceof Array) {

Perform certain operations on an array

}

(2) if (Array.isarray (value)) {

Perform certain operations on an array

}

Conversion method:

(1) toString (); Converts the array to a string and returns the result.

Example: var arr = [N, "123", "a", "old"];

Console.log (Arr.tostring ());

12,123,45,old

(2) valueOf (); Returns the original value of an array object

Example:

var arr = [N, "123", "a", "old"];

Console.log (Arr.valueof ());

[123], "old"

(3) tolocalestring (); Converts the array to a local array and returns the result.

<script type= "Text/javascript" >
var arr = new Array (3)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
document.write ( arr.toLocaleString() )
</script>
George, John, Thomas.

(4) join (); Put all the elements of the array into a string. element is delimited by the specified delimiter.

Example: var colors = ["Red", "Blue", "green"];

Alert (Color.join ("| |)");

var arr = [N, "old", +, "young"];

Console.log (Arr.join (| |));

12| | old| | 14| | Young

Stack method: LIFO (Last-in-fisft-out)

Inserting and removing data that occurs only at the top of the stack

(1) push () can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array

Cases:

var arr = [];

Arr.push (1);//return array length 1

arr;//[1]

Arr.push (2,3);

arr;//[+]

(2) Pop () removes the last item from the end of the array and returns the removed item

var arr = [1, 2, 3];

Arr.pop ();//Return 3

arr;//[up]

Queue method: FIFO (First-in-first-out)

End of Queue list Add Item, remove item from front end of list

(1) push () can receive any number of parameters and add them to the end of the array individually

(2) Shift () moves the first item of the divisor group and returns the item

var arr = [1, 2, 3];

Arr.shift ();//return 1

arr;//[2,3]

Sort by:

(1) reverse (): Reverses the order of the array

var arr = [1, 2, 3];

Arr.reverse ();//[3, 2, 1]

arr;//[3, 2, 1]

(2) Sort: Arranging arrays in ascending order

Functions: Sorting elements in an array

Syntax: sort ([SortBy])

Parameters:

If the SortBy parameter is not specified, the default order is sorted alphabetically;

SortBy is a function name that specifies the collation of the element

Arr.sort (by the above); Pass the address of the function to the Sort method

function by (A, B)

{

return a-B; Sort the numeric size

}

Results of A-B:

A-B >0 returns a value greater than 0

A-b = 0 Returns a value equal to 0

A-b < 0 returns values less than 0

To sort numbers by the size of a number, you must use a sort function to achieve this:

<script type= "Text/javascript" >
function Sortnumber (A, B)
{
Return A-B
}
var arr = new Array (6)
Arr[0] = "10"
ARR[1] = "5"
ARR[2] = "40"
ARR[3] = "25"
Arr[4] = "1000"
ARR[5] = "1"
document.write (arr + "<br/>")
document.write ( arr.sort(sortNumber) );
</script>

Connection method:

Concat (): Method for connecting two or more arrays

<script type= "Text/javascript" >
var arr = new Array (3)
Arr[0] = "George"
ARR[1] = "John"
ARR[2] = "Thomas"
var arr2 = new Array (3)
Arr2[0] = "James"
ARR2[1] = "Adrew"
ARR2[2] = "Martin"
document.write ( arr.concat(arr2) )
</script>
Results
George,john,thomas,james,adrew,martin

To get the Subarray method:

Slice (): Returns the selected element from an existing array

Arrayobject.slice (Start,end)

Parameters

Describe

Start

Necessary. Specify where to start the selection. If it is a negative number, it specifies the position from the end of the array. In other words, 1 refers to the last element, 2 refers to the second-lowest element, and so on.

End

Optional. Specifies where to end the selection. The parameter is the array subscript at the end of the array fragment. If this parameter is not specified, then the segmented array contains all elements from start to end of the array. If this parameter is a negative number, it specifies the element starting from the end of the array.

return value

Returns a new array containing elements from start to end (excluding the element) from the Arrayobject.

Slice (start subscript, end subscript (optional, default to array length))

[' A ', ' B ', ' C ', ' d '].slice (1);//["B", "C", "D"]

[' A ', ' B ', ' C ', ' d '].slice (1, 2);//["B"]

[' A ', ' B ', ' C ', ' d '].slice (1, 3);//["B", "C"]

(3) Splice ()

Splice (start subscript, delete number, insert element (can be multiple))

var arr = [1, 2, 3, 4];

Arr.splice (1, 2);//[2,3]

arr;//[1,4]

arr = [1, 2, 3, 4];

Arr.splice (1, 2, ' A ', ' B ', ' C ');//[2,3]

arr;//[1, "A", "B", "C", 4]

Location Method:

(1) indexOf (): Find the subscript where the element is located, and return if it can be found. Otherwise returns-1

[' A ', ' B ', ' C ', ' d '].indexof (' C '); 2

[' A ', ' B ', ' C ', ' d '].indexof (' G '); -1

(2) LastIndexOf (): Looking forward from the end

[' C ', ' d ', ' C '].lastindexof (' C '); 2

[' A ', ' B ', ' C ', ' d '].lastindexof (' G '); -1

Iterative methods: Run a given function on each item of an array

(1) Whether each element in the every () array satisfies the specified condition.

var isallpositive = [3, 4, -1].every (function (each) {

return each > 0;

});

isallpositive; False

Isallpositive = [3, 4].every (function (each) {

return each > 0;

});

isallpositive; True

(2) filter () finds all elements that meet the specified criteria from the array.

Find all positive numbers

var res = [3, 4, -1].filter (function (each) {

return each > 0;

});

Res [3,4]

(3) ForEach () iterates through the array.

[' A ', ' B ', ' C '].foreach (function (item, index, arr) {

Console.log (Item,index);

});

Output ' A ' 0 ' B ' 1 ' C ' 2

(4) Map () maps an array to another array.

Content * 2

[1, 2, 3].map (function (each) {

return each * 2;

});

The some () array has elements that meet the specified criteria.

Whether there is a positive number

var issomepositive = [3, 4, -1].some (function (each) {

return each > 0;

});

issomepositive; True

Issomepositive = [ -3, -4].every (function (each) {

return each > 0;

});

issomepositive; False

Merge method:

Reduce ():

Reduce (function (Prev,cur,index,array) {

})

Parameters:

Prev: Previous value

Cur: Current Value

Index: Indexes of items

Array: Arrays Object

From the beginning of the first item of the array, iterate through to the end, combining the array with a value.

The array contents are summed. 0 is the initial value

[1, 2, 3].reduce (function (prev, each) {

return prev + each;

}, 0);

Returns 6

Reduceright (): Starts with the last item in the array, traversing through to the first item

Iterate through an array:

JavaScript Summary-Arrays

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.