JavaScript Arrays (Array) Detailed _ Basics

Source: Internet
Author: User
Tags data structures prev

An array of ECMAScript differs considerably from an array in other languages. Although the array in ECMAScript also has a sequence table, it is an array of your every item can hold any type of data. The size of the ECMAScript array can be dynamically adjusted.
There are two basic ways to create an array. The first is to use the array constructor, as follows:

Copy Code code as follows:

var colors = new Array ();

If you know the number of items to save for an array, you can also pass parameters to the constructor, which automatically becomes the value of the length property, as follows:
Copy Code code as follows:

var colors = new Array (20);

You can also pass the items that should be included in the array to the arrays constructor, as shown in the following code:
Copy Code code as follows:

var colors = new Array ("Red", "blue");

Also, you can omit the new operator when you use the array constructor, as follows:
Copy Code code as follows:

var colors = Array (20);

The second way to create an array is to use an array literal notation. The literal amount of an array is represented by a pair of square brackets that contain an array item, separated by commas between multiple array items, as follows:
Copy Code code as follows:

var color = ["Red", "Blue"];
var names = [];
var values = [1,2,]//ie8 and previous 3, other 2 items, not recommended

As with objects, the array's constructor is not invoked when numeric literal notation is used.
When reading and setting the value of an array, you use the square brackets and provide a 0-based numeric index of the corresponding values, as follows:
Copy Code code as follows:

var colors = ["Red", "Blue"]; Defining arrays
Alert (colors[0]); Red
COLORS[1] = "BLACK"//Modify Item 2nd
COLORS[2] = "Brown"//Add 3rd

The number of items in the array is saved in its Length property, which always returns a number of 0 or greater, as follows:
Copy Code code as follows:

var colors = ["Red", "Blue"]; Defining arrays
var names=[];
alert (colors.length); 3
Alert (names.length)//0

It is worth noting that the length value of the array is not read-only. Therefore, by setting this value, you can move the item from the end of the array or add items to the array as follows:
Copy Code code as follows:

var colors = ["Red", "Blue"];
Colors.length = 1;
Alert (colors[1]); Undefined

You can also easily add data to the end of an array by using the Length property:
Copy Code code as follows:

var colors = ["Red", "Blue"];
Colors[colors.length] = "BLACK"; At location 2 new
Colors[colors.length] = "Brown"; At location 3 new

1. Detection array

For a Web page or a global scope, the instanceof operator can be used to:

Copy Code code as follows:

if (value instanceof Array) {
Perform an action
}

The limitations of the instanceof operator are global scopes, where more than two global execution environments exist if the Web page contains multiple frames. To solve this problem, ECMAScript5 has added the Array.isarray () method, using the following:
Copy Code code as follows:

if (Array.isarray (value)) {
Perform an action
}

2. Transformation method
the call to the ToString () method of the array returns a comma-delimited string of strings of each value in the array. The call valueof () returns or an array. As shown below:

Copy Code code as follows:

var colors = [' Red ', ' blue ', ' green '];
Alert (colors.tostring ()); Red,blue,green
Alert (colors.valueof ()); Red,blue,green
Alert (colors)//red,blue,green

Array inherits the Tolocalstring (), tistring (), and valueof () methods, which, by default, return the array entries as a comma-delimited string. If you use the Join () method, you can use a different separator to build this string. The join () method takes only one argument, the string used as a delimiter, as follows:
Copy Code code as follows:

var colors = [' Red ', ' blue ', ' green '];
Alert (Colors.join (', ')); Red,blue,green
Alert (colors.join (' | ')); Red|blue|green

If a value in the array is null or undefied, the value is represented in an empty string by the join (), tolocalstring (), tistring (), and valueof () methods.

3, Stack method

JavaScript provides push () and pop () operations specifically for arrays to implement stack-like behavior.

The push () method can receive any number of arguments, adding them individually to the end of the array and returning the length of the modified array. The Pop () method overflows the last item from the end of the array, reduces the length of the array, and then returns the removed item.

Copy Code code as follows:

var colors = new Array (); Defining arrays
var count = Colors.push ("Red", "blue"); Press into two items
alert (count); 2
Count = Colors.push ("Black"); Press into another item
alert (count); 3
var item = Colors.pop (); Eject the last one
alert (item); "Black"
alert (colors.length); 2

4. Queue method

The access rules for stack data structures are LIFO (LIFO), while the access rules for Queues are FIFO (first-in first Out). The queue adds items at the end of the list and moves out of the front end.

The shift () method moves the first item in the divisor group and returns the item, the length-1 of the array. Combining the push () and Shift () methods, you can use arrays as you would with queues, as follows:

Copy Code code as follows:

var colors = new Array ();
var count = Colors.push ("Red", "blue");
Count = Colors.push ("Black");
alert (count);
var item = Colors.shift (); Get the first
alert (item); "Red"
alert (color.length); 2

ECMAScript also provides the Unshift () method for the array. The Unshift () and Shift () methods use the opposite: it adds any items to the front of the array and returns the length of the new array. Therefore, using both the Unshift () and Shift () methods, you can simulate the queue in the opposite direction by adding a new item to the front of the array and moving it from the end of the array as follows:

Copy Code code as follows:

var colors = new Array ();
var count = Colors.push ("Red", "green");
alert (count); 2
Count = Colors.unshift ("Black"); Push another item
alert (count); 3
var item = Colors.pop (); Get the last one
Alert (item)//green
Alert (colors.length)//2

5. Reordering methods
There are already two methods in the array that can be used directly for reordering: reverse () and sort (). The reverse () method sorts by reversing the array items.

Copy Code code as follows:

var values = [2, 1, 3, 4, 5];
Values.reverse ();
alert (values); 5,4,3,2,1

By default, the sort () method arranges array items in ascending order, invokes the ToString () method for each item, and compares strings to determine how to sort. Even if each item in the array is a numeric value, the sort () method compares the strings.
Copy Code code as follows:

var values = [12, 11, 3, 4, 5];
Values.sort ();
alert (values); 12,11,3,4,5

We can pass a comparison function as a parameter to the sort () method. As follows:
Copy Code code as follows:

function Compare (value1, value2) {
if (value1 < value2) {
Return-1
else if (value1 > value2) {
Return 1
} else {
return 0
}
}
var values = [0, 1, 5, 10, 15];
Values.sort (Compare);
alert (values); 0,1,5,10,15

6. Operation Method
ECMAScript provides a number of methods for operations in an array. where the concat () method can create a new array based on all the items in the current array.

Copy Code code as follows:

var colors = ["Red", "green", "blue"];
var colors2 = Colors.concat ("Yellow", ["Black", "Brown"]);
alert (colors); Red,green,blue
alert (COLORS2); Red,green,blue,yellow,black,brown

Slice () method that creates a new array based on one or more items of the current array, and it can receive one or two parameters, that is, to return the starting and ending positions of the items. A parameter, returns all items at the beginning of the specified position to the end of the current array. Two parameters return all items starting to the specified position-not including the end position. Note that the Slipe () method does not affect the original array.
Copy Code code as follows:

var colors=["Red", "green", "Blue", "Black", "Brown";
var colors2=colors.slice (1);
var colors3=colors.slice (1,4);
alert (COLORS2); Green,blue,black,brown
alert (COLORS3); Green,blue,black

Slice () method deletion: You can delete any number of items by specifying only 2 parameters: the position of the first item to delete and the number of items to delete.
Slice () method insert: You can insert any number of items to a specified location by providing only 3 parameters: Start position, 0 (number of items to delete), and items to insert.
Slipe () method substitution: You can insert any number of items at the specified position of the item and delete any number of items at the same time, specifying only 3 parameters: The starting position, the number of items to delete, and any number of items to insert.
Copy Code code as follows:

var colors = ["Red", "green", "blue"];
Delete
var removed = colors.slice (0, 1); Delete Item 1th
var colors3 = Colors.slice (1, 4);
alert (colors); Green,blue
alert (removed); Red
Insert
removed = Colors.slice (1, 0, "yellow", "orange"); Insert starting from position 1
alert (colors); Green,yellow,orange,blue
alert (removed); Empty array
Replace
removed = Colors.slice (1, 1, "Red", "purple"); Insert starting from position 1
alert (colors); Green, "Red", "purple", Orange,blue
alert (removed); "Yellow"

7. Location method
ECMAScript5 provides two location methods for an array: IndexOf () and LastIndexOf (). Both methods receive two parameters: the item to find and an optional index that represents the start position of the lookup. where the IndexOf () method looks at the beginning of the array, the LastIndexOf () method starts looking forward from the end of the array.
Both methods return the position of the item to find in the array and return 1 if not found.

Copy Code code as follows:

var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
Alert (Numbers.indexof (4))//3
Alert (Numbers.lastindexof (4))//5
Alert (Numbers.indexof (4, 4))//5
Alert (Numbers.lastindexof (4, 4))//3

8. Iterative Method

ECMASCRIPT5 defines 5 iteration methods for an array. Each method accepts two parameters, the first is the function that is iterated, and the second is the scope object "optional" for the function.

The function of the iteration accepts three parameters, the first is the value of the element to be iterated in the array, the second is the position of the element to be iterated by the array, and the third is the iteration group itself.

1. Every () each item in the array runs the given function, and returns TRUE if the function returns true for each item
2. Filter () Each item in the array runs the given function, which returns an array of the items that the function returns True.
3. Each item in a ForEach () array runs a given function, and this method does not return a value of 4. Map () Each item in the array runs the given function, returning an array of the results of each function call
5. Some () each item in the array runs the given function, and returns TRUE if the function returns true for any of the items
These iterative methods are supported by browsers that have, Ie9+,firefox2+,safari3+,opera 9.5+,chrome
Among these methods, the most similar is every () and some (), which are used to query whether an item in an array satisfies a condition. For every (), the passed in function must return true for each item, and this method returns true, otherwise he returns false. The Some () method returns True whenever an entry in an array of functions returns TRUE.

Copy Code code as follows:

var num = [1,2,3,4,5,6,7,8,9];
var everyresult = num.every (function (item, index, array) {
if (item > 2) {
return true;
}
});
alert (Everyresult); False
var someresult = num.some (function (item) {
if (item > 2) {
return true;
}
});
alert (Someresult); True

Filter () uses the specified function to determine whether an item is included in the returned array.

Copy Code code as follows:

var num = [1,2,3,4,5,4,3,2,1];
var filterresult = num.filter (function (item) {
if (item > 2) {
return true;
}
});
alert (Filterresult); [3,4,5,4,3]

Map () also returns an array, and each item of the array is the result of running the passed-in function on the corresponding item in the original array.

Copy Code code as follows:

var num = [1,2,3,4,5,4,3,2,1];
var mapresult = Num.map (function (item) {
if (item > 2) {
return true;
}
}); [2,3,6,8,10,8,6,4,2]

ForEach () is the function that is passed in for each item in the array. This method has no return value and is essentially the same as using a For loop iteration group.

Copy Code code as follows:

var num = [1,2,3,4,5,4,3,2,1];
Num.foreach (function (item) {
Perform an action
});

9. Merging method

There are two new methods in ECMAScript5: Reduceright () and reduce (). Both methods accept two parameters: the first is the function of an array to iterate over, and the function has four parameters, the previous value, the current value, the index of the item, and the array object. However, any value of this function will be automatically passed to the next item as the first argument. The second is the initial value of the first parameter in the first function.

Copy Code code as follows:

var nums = [1,2,3,4,5];
var sum = nums.reduce (function (prev, cur, index, array) {
return prev + cur;
});
alert (sum);//15

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.