The basic text of the JavaScript array

Source: Internet
Author: User
Tags object object javascript array

Organized the Array of very basic to grasp the knowledge points, hope to help beginners, but also hope that their future more use more mastery.

Create an array

    • Use the array constructor:
var a=New Array (); // create an empty array var a=New Array (20); // An array that creates the number of items for a given number var a=New Array ("A", "B", "C"); // an array that contains 3 string values var a=array (); // you can omit the New keyword var a=array (3);

You can also create an array by passing a value to the constructor:

    1. If a numeric value is passed, an array of number of given items is created
    2. If you pass a parameter of another type, you create an array of only one item that contains that value.

    • Use the array literal notation:
var a=[' A ', ' B ', ' C ']; // create an array with three strings var a=[]; // create an empty array

Not recommended:

Cause: The ECMAScript implementation in the <=IE8 version exists in the array literal bug,a becomes a 3 item with a value of [1,3,undefined] , [undefined,undefined, Undefined] (this result is logically the same as the new Array (3) )

Array Length Property

The length property of an array is not read-only (it is not clear why the value of the values attribute is always the value of the second item of the array, and when the array length<=1 , the Object.getownpropertydescriptor (a,length) return for undefined , know the pot friends thanks to inform! )。

So by setting this property, you can remove an item from the end of the array. However, if length is set to a value that is greater than the number of array items, the following value will be undefiend .

var a=[' A ', ' B ', ' C '];a.length=2; Console.log (a[2]); // undefined

You can add items to the array

var a=[' A ', ' B ', ' C '];a[a.length]= ' d ';//["A", "B", "C", "D"]

When you place a value beyond the current array size, the array recalculates its length.

var a=[' A ', ' B ', ' C '];a[99]= ' P '; a.length; // [a[3]; // a[3]~a[98] All for undefined

detecting arrays

    • A instanceof Array; // true Determine if A is an instance of Array

Cons:  instanceof   Assume that there is currently only one global execution environment. If you have more than one frame in a Web page, there are more than two different global execution environments, and there are more than two different versions of  window   different versions of  < Span class= "Cnblogs_code" >array   constructors, if you enter an array from one frame to another, the array that is passed into the array and the target frame may have different constructors, so you cannot tell if it is an instance. The above code returns &NBSP;true  ,a must be an array and  array   constructors are in the same global scope, and  array   is also a property of  window  . If a is an array defined in another  frame  , then the above code will return  < Span style= "color: #0000ff;" >false  . wrote a different framework reference data test, but also involved in Chrome because of the origin of some problems, interested in the poke http://www.cnblogs.com/venoral/p/5232676.html

    • Array.isarray (a); //   true No environment, just determine whether a certain value is finally determined to be an array
    • Object.prototype.toString.call (a) the constructor name array of the native array is independent of the global scope, and toString () is used to guarantee that a consistent value is returned.

Calling the object 's native toString () method on any value will return a string in [object Nativeconstructorname] format, with one inside each class [[Class]] property, which specifies the name of the constructor in the preceding string. Based on this approach, it is also possible to detect whether a value is a native function or a regular expression. However, the constructor name of a non-native constructor cannot be detected, and any custom constructor will return [Object Object] .

The various array methods described below are from Array.prototype

Conversion method  

var a=[' A ', ' B ', ' C '];a.tostring (); // "A,b,c" in order to create this string will call every item of the array ToString () method, if A.tolocalestring () will call the array of each item tolocalestring ()
A.valueof ();//["A", "B", "C"]

The toString () method of the call array returns a comma-delimited string of strings for each value in the array, but the call to valueOf () returns the array

a.join ();//"A,b,c" a.join (undefined);//"A,b,c" A.join (' | | '); /"a| | b| | C

The Join () method receives only one parameter, the string that is used as a delimiter, and returns a string that contains all the array items. Do not pass any value to join () or pass in undefined (<=ie7 uses the undefined delimiter) to use a comma as the delimiter.

If an item in the array has a value of null or undefined , then the value is in join () , tolocalestring () , toString () , the valueOf () method returns an empty string representation of the result.

a=[3,undefined,null, '];a.tostring (); // "3,,,"

Stack method

The push () method accepts any number of arguments (parameters can be multiple, multiple parameters are added in order from left to right), they are added one at a to the end of the array, and the modified array length is returned.

The pop () method removes the last item from the end of the array, reduces the length of the array, and returns the item that is removed.

Queue method

shift () shifts the first number in the array and returns the item, reducing the length of the arrays by one. Using the shift and push methods together, you can use arrays as you would with queues.

unshift () adds any item at the front of the array (the multi-parameter add order first right and left) and returns the new array length (<=IE7 returns undefined ). Use both the unshift and pop methods to simulate the queue in the opposite direction.

var a=[' A ', ' B ', ' C '];a.unshift (' o ', ' P ', ' Q ');//6
A ["O", "P", "Q", "A", "B", "C"]

Reorder Methods

reverse () reverses the order of the array items, returning the original array after the reversal.

The sort () method arranges the array items in ascending order, returning the sorted original array . In order to implement the sort, the sort () method invokes the toString () transformation method of each array item, and then compares the resulting string to determine how to sort (the individual feels that it is compared by the ASCII table, sort There is no definition in the implementation criteria of the internal comparison sorting algorithm, which may be bubbling or fast-running, which is interesting to refer to my other article http://www.cnblogs.com/venoral/p/5180439.html). Even if each item in the array is a numeric value, the sort () method compares the string, see the following code

When the string comparison is made, "10" is preceded by "5", against the ASCII table, the decimal of "1" is 49, and the decimal of "5" is 53. The sort () method can therefore receive a comparison function (receiving two parameters) as a parameter, in order to consider specifying which value is in front of which value.

var compare=function(value1,value2) {   ifreturn -1;    Else if return 1;    Else return 0}var a=[1,5,10,6];a.sort (Compare);//[1,5,6,10]

For numeric types or their valueOf () methods, the object type of a numeric type can be returned using a simpler comparison function that only requires the second value minus the first value to produce a descending result (ascending is a meiosis and a meiotic interchange). This can be done because the sort () interior is based on a return of less than 0, greater than 0, which equals zero to affect the sorting result.

var compare=function(value1,value2) {  return value2-value1;} var a=[1,5,10,6];a.sort (compare); // [Ten, 6, 5, 1]

Operation method

concat () creates a new array based on all the items in the current array. This method creates a copy of the current array, adds the received parameters to the end of the copy, and returns the newly constructed array.

    1. In the absence of a parameter, it simply copies the current array and returns a copy.
    2. The concat () method is passed to one or more arrays, which adds each item in the array to the result array.
    3. The value passed is not an array, and the values are simply added to the end of the result array.

Slice () , translated to "cut out", it can create a new array based on one or more items in the current array. The slice method accepts one or two parameters, that is, to return the starting and ending positions of the item.

    1. Without a parameter, returns a new array of copies of the original array.
    2. Returns all items from the specified position of the parameter to the end of the current array, with only one parameter.
    3. Two parameters that return the entry between the starting position and the end position (but not the end position).
    4. In the case of a negative number in the parameter, the corresponding position is determined by adding the negative number to the array length. Returns an empty array if the end position is less than the starting position. If the calculated position is still negative, it is just copying the current array and returning the copy.

splice () , translated to "splicing", the main purpose is to insert an item into the middle of the array, the use of the method will change the original array . Splice () always returns an array that contains items that were deleted from the original array (an empty array is returned if no items were deleted)

    • Delete: You can delete any number of items and return the deleted items.
    1. Without parameters, no items are deleted.
    2. With only one parameter, all items at the end of the current array are deleted.
    3. Two parameters: The position of the first item to delete and the number of items to delete.
    4. In the case of a negative number in the parameter, the corresponding position is determined by adding the negative number to the array length. An empty array is returned if the number of items to be deleted is negative.

    • Insert: You can insert any number of items at the specified location, three parameters: Start position, 0 (number of items to delete), the item to insert, and if you want to insert more than one item, you can pass in as many items again.

    • Replace: You can insert any number of items to the specified location and delete any number of items at the same time. Three parameters: The starting position, the number of items to be deleted, and any number of items to insert.

Location method

Both indexOf () and lastIndexOf () Accept two parameters: the item to find, optionally, an index that represents the location of the lookup start point. Returns the position of the item to find in the array, and returns 1 if no case is found. The congruent operator is used when comparing the first argument to each item in the array.

indexOf () looks backwards from the beginning of the array (position 0), and lastIndexOf () looks forward from the end of the array.

A=[' A ', ' B ', ' C ', ' d ', ' E ', ' B '];a.indexof (' B ', 2); // 5a.lastindexof (' B ', 0); // -1a.lastindexof (' B ', 5); // 5
var person={name: ' xx '}; var people1=[{name: ' xx '}]; var people2=[person];p eople1.indexof (person); // -1people2.indexof (person); // 0

Iterative methods

Each iteration method receives two parameters: the function's scope object (that is, the value that affects this) that is to be run on each item. The functions passed in these methods can receive 3 parameters: the value of the array item, the position of the item in the array, and the array object itself .

Depending on the method used, the return value after the function is executed may or may not affect the return value in the method.

    •  every ()  : If the function returns  < Span style= "color: #0000ff;" >true  , the entire array is called after the function returns a value of  true  .
    •  filter ()  : Returns the array returns   true   's constituent array . This method is useful for querying all array items that meet certain criteria.
    •  foreach ()  : no return value.
    •  map ()  : Returns the array that consists of the result of each function call . This method is suitable for creating an array containing the items corresponding to another array of one by one.
    •  some ()  : If the function returns  < Span style= "color: #0000ff;" >true  , returns  true  .

The difference between every () and Some () :

A=["A", "B", "C", "D", "E", "B"];a.every (function(item,i,array) {  return  typeof item== ' string '}); // truea.some (function(item,i,array) {  return item== ' B ';}); true
// Determines whether an item A.filter (functionreturn item== ' B '}) is included in the returned array using the specified function ; // ["B", "B"] // each item of the returned array is the result of running the passed-in function on the basis of the corresponding item in the original array a.map (function(item,i,array) {  return item+ ' xx ';}); // ["Axx", "bxx", "cxx", "dxx", "Exx", "bxx"]

Merging array methods

reduce () and reduceright () , both of which iterate over all items in an algebraic group and then build a value that is ultimately returned. All receive two parameters: the function that is called on each item (receives 4 parameters: the previous value, the current value, the index of the item, the array object), as the initial value of the merge base (optional). Any value returned by this function is automatically passed to the next item as the first argument.

Note: If you omit the incoming initial value, the first iteration occurs on the second item of the array, so the first parameter is the first item of the array, and the second is the second item of the array.

reduce () starts from the first item in the array, traversing through to the end.

reduceright () starts from the last item in the array and traverses forward to the first item.

reference : JavaScript advanced Programming

The basic text of the JavaScript array

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.