JavaScript array type (array) __java

Source: Internet
Author: User
Tags array length prev javascript array
JavaScript array type (array) 1. Introduce 1.1 Definition
The first method: through the constructor Array//Note: You can omit the new keyword
var colors = new Array ();
var colors = new Array;
var colors = new Array ();
The second method: the literal amount of the array
var colors = [];
var colors = ["Blue", "Black", "green"];
1.2 using and assigning values
var colors = ["Blue", "Black", "green"];
Alert (colors[0]);    Use
colors[2] = "BLACK";//Assign value
colors[3] = "Brown";//New
1.3 Length Property

The Length property is not read-only. \
You can add or remove items from the end of an array by setting this property, and the new entry defaults to undefined\
The length property makes it easy to add items to the end of an array.

var colors = ["Blue", "Black", "green"];
Colors[colors.length] = "BLACK";
Colors[colors.length] = "Brown";

COLORS[99] = "white";
alert (colors.length); 100
2. Detection array: Array.isarray ()

The problem with using the instanceof operator is that it assumes that there is only one global execution environment. If more than one framework is used in a project, there are more than two global execution environments with more than two versions of the array constructor. \
To solve this problem, ECMASsript5 added Array.isarray (). The purpose of this method is to determine in the end whether a value is an array.

var bool = value instanceof Array;
var bool = Array.isarray (value);
3. Conversion method: toLocaleString (), toString (), valueof (), join ()

Each object in JS has a conversion method: toLocaleString (), toString (), and valueof () methods.
- ToString () returns a comma-delimited string of each string in the array, which, in order to create this string, invokes the ToString () method of each item;
- tolocalestring () returns a comma-delimited string of each string in the array, in order to create the string, the toLocaleString () method;
- valueof () return or array;
- Join () you can use different delimiters to build an array string; 4. Add Delete: Push (), pop (), Shift (), Unshift ( ) push ( ): Add pop () at end () : Remove shift (): Front end Remove unshift (): Front-End add stack : LIFO (LIFO), the operation of the stack of items only occurs in one position-the top of the stack. You can use push (), pop () implementations. Queue : Advanced First Out (FIFO), end added, front end removed. You can use push (), shift () implementation. 5. Reordering method: Reverse (), sort () reverse (): Reverse sort (): Sort \
The return value is the sorted array

The simplest example:
var array = [1,2,3,4,5];
var-i = Array.reverse ();  [5,4,3,2,1]
var second = First.reverse ();  [1,2,3,4,5]

In the above example, the Reserse () method is straightforward, but not flexible enough to meet our custom collation requirements. So the sort () method is available. The sort () method is sorted by default in ascending order. To implement sorting, the method automatically invokes the ToString () method of each array item and compares the string for sorting. Such as:

var array = [0,1,5,10,15];
var result = Array.Sort (); [0,1,10,15,5]
//Here you will get results that are not based on numbers.

The great thing about the sort () method is that it accepts a comparison function as a parameter , which enables us to customize the collation. The comparison function receives two parameters, represents two items in an array, take up a,b indicates that if a should be before B, a negative number is returned (indicating no swap position), and if a should be after B, a positive number is returned (indicating that the swap position is required), or 0 if a equals B. Cases:

Comparison method
function compare (a,b) {
    if (a<b) {
        return-1;
    } else if (a>b) {return
        1;
    } else { Return
        0
    }
}

Use the above comparison method to implement the ascending
var array = [0,1,5,10,15];
var result = Array.Sort (compare); [0,1,5,10,15]

By using the above form, you can achieve a more complex sort effect. 6. Method of Operation: Concat (), slice (), splice () concat (): Merging arrays without affecting the original array \
The Concat () method first creates a copy of the current array, then adds the received parameter to the end of the replica, and finally returns the newly created array.

var colors1 = [' Red ', ' green '];
var colors2 = colors1.concat (' Yellow ', [' Blue ', ' black ']);
colors2 = [' Red ', ' green ', ' yellow ', ' blue ', ' black ']

Slice (): Cut array without affecting the original array \
Slice () builds a new array based on one or more items of the current array. Accept one or two parameters.

var colors1 = [' Red ', ' green ', ' yellow ', ' blue ', ' black '];
If there is only one argument, the array
var colors2 = colors1.slice (1) from the specified position to the end position of the parameter is returned.     [' green ', ' yellow ', ' blue ', ' black ']
///If there are two parameters, returns the array of the first argument to the item specified in the second argument (not containing) the
var colors3 = Colors1.slice (1,4);   [' green ', ' yellow ', ' blue ']
//If there is a negative number in the argument, use the array length plus the parameter to determine the position
var colors4 = Colors1.slice ( -4,-1);//[' green ', ' Yellow ', ' blue ']
///If the second argument is less than the first argument, an empty array of
var colors5 = Colors1.slice (2,1) is returned;   //[]

splice (): splicing (delete, insert, replace), to the original array operation \
With splice, you can delete, insert, replace operations on the original array, and always return an array that contains items that were removed from the original array. Delete : Receive two parameters: the first position to delete and the number of items to delete; Insert : Receive more than three parameters: start position, 0 (number of items to delete), items to insert, replace : Receive three or more parameters: Start position, number of items to delete , the item to insert;

var colors = [' red ', ' green ', ' yellow ', ' blue ', ' black '];
Delete
var removed = Colors.splice (0,1);  [' Red ']
//colors = [' green ', ' yellow ', ' blue ', ' black ']

///insert
var removed = Colors.splice (1,0, ' white ', ' Orange '); []
//colors = [' green ', ' white ', ' orange ', ' yellow ', ' blue ', ' black ']

//replace
var removed = Colors.splice ( 1,1, ' red '); [' White ']
//colors = [' green ', ' red ', ' orange ', ' yellow ', ' blue ', ' black ']
7. Location method: IndexOf (), LastIndexOf ()

The Exmascript adds two location methods. Both methods receive two parameters: the item to find and the index of the location to start the lookup. The return value is the position of the item to find in the array, and no return-1 is found. Use the strict equality operator in the lookup process.
- indexOf () positive sequence
- LastIndexOf () reverse sequence

' var number
= [1,2,3,4,5,4,3,2,1];
Alert Number.indexof (4);       3
Alert Number.lastindexof (4);   5
Alert Number.indexof (4,4);     5
Alert Number.lastindexof (4,4);//3
'
8. Iterative method: Every (), filter (), ForEach, Map (), some ()

5 iterative methods that receive two parameters: the function to run on each item and the scope object that is running the function (affect this). The function passed in receives three parameters: the value of the current array item, the item's position in the array, and the array itself.
- every () : Runs the given function for each item in the array and returns true if the result is all true;
- Some () : Each item in the array runs the given function, and returns True if one of the results is true;
- filter () : Each item in an array runs the given function, returning a new array of array items with the result of true;
- ForEach () : Each item in the array runs the given function with no return value;
- map () : Each item in the array runs the given function, returning an array of running results for each item;
none of the above methods will modify the original array

' var number
= [1,2,3,4,5,4,3,2,1];
var everyresult =  number.every (function (item,index,array) {return
    (item>2);
});   False

var someresult = Number.some (Functon (item,index,array) {return
    (item>2);
});   True

var filterresult = number.filter (function (item,index,array) {return
    (item>2);
})   [3,4,5,4,3]

var mapresult = Number.map (function (item,index,array) {return
    (item*2);
});  [2,4,6,8,10,8,6,4,2]

//foreach method does not return a value
Number.foreach (function (item,index,array) {
    //Perform action
});
```
9. Merge method: Reduce (), reduceright ()

ECMAScript5 New method. Both of these methods will iterate over all the items of the group and build a final return value. Accept two parameters: a function called on each item and an initial value that is the base of the merge. The first parameter accepted is a function that receives 4 parameters: = = Previous value, current value, item index, array object = =; Any value returned by this function is automatically passed to the next item as the first argument. Two functions are performed in different directions, except that they are identical.
- reduce () positive sequence
- reduceright () reverse sequence
"'
Array summation:
var number = [1,2,3,4,5];
var sum = number.reduce (function (prev, cur, index, array) {
return prev + cur;
}); 15

var sum = number.reduceright (function (prev, cur, index, array) {return
    prev + cur;
});    ""

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.