分类: Javascript

Professional Javascript For Web Developers – Array Type






THE ARRAY TYPE

After the Object type, the Array type is probably the most used in ECMAScript
ECMAScript arrays are ordered lists of data, but unlike in other languages, they can hold any type of data in each slot. This means that it’s possible to create an array that has a string in the first position, a number in the second, an object in the third, and so on.
Arrays can be created in two basic ways. The first is to use the Array constructor, as in this line:

	
	var colors = new Array();


If you know the number of items that will be in the array, you can pass the count into the constructor, and the length property will automatically be created with that value. For example, the following creates an array with an initial length value of 20:

	var colors = new Array(20);

The second way to create an array is by using array literal notation
Array literal is specified by using square brackets and placing a comma-separated list of items between them, as in this example:

	
	var colors = [“red”, “blue”, “green”]; //creates an array with three strings The Array Type 
	var names = []; //creates an empty array
	var values = [1,2,]; //AVOID!Creates an array with 2 or 3 items 
	var options = [,,,,,];  //AVOID! creates an array with 5 or 6 items

A unique characteristic of length is that it’s not read-only. By setting the length property, you can easily remove items from or add items to the end of the array. Consider this example:

	
	var colors = [“red”, “blue”, “green”]; //creates an array with three strings 
	colors.length = 2; 
	alert(colors[2]); //undefined

The length property can also be helpful in adding items to the end of an array, as in this example:

	var colors = [“red”, “blue”, “green”]; //creates an array with three strings
	colors[colors.length] = “black”;  //add a color (position 3)
	colors[colors.length] = “brown”;  //add another color (position 4) 
	//The last item in an array is always at position length – 1,

Detecting Arrays

Ever since ECMAScript 3 was defined, one of the classic problems has been truly determining whether a given object is an array
ECMAScript 5 introduced the Array.isArray() method

	if (Array.isArray(value)){ 
	//do something on the array 
	}
Stack Methods

One of the interesting things about ECMAScript arrays is that they provide a method to make an array behave like other data structures.
A stack is referred to as a last-in-first-out (LIFO) structure, meaning that the most recently added item is the first one removed.
ECMAScript arrays provide push() and pop() specifically to allow stack-like behavior.
The push() method accepts any number of arguments and adds them to the end of the array, returning the array’s new length.
The pop() method, on the other hand, removes the last item in the array, decrements the array’s length, and returns that item.
Consider this example:

	var colors = new Array(); 			//create an array
	var count = colors.push(“red”, “green”); 	//push two items
	alert(count); //2 

	count = colors.push(“black”); 			//push another item on
	alert(count); //3 

	var item = colors.pop(); 			//get the last item
	alert(item); //”black” 
	alert(colors.length); //2
Queue Methods

Just as stacks restrict access in a LIFO data structure, queues restrict access in a first-in-first-out (FIFO) data structure.
A queue adds items to the end of a list and retrieves items from the front of the list. Because the push() method adds items to the end of an array, all that is needed to emulate a queue is a method to retrieve the first item in the array. The array method for this is called shift(), which removes the first item in the array and returns it, decrementing the length of the array by one.

	var colors = new Array(); 
	var count = colors.push(“red”, “green”); 
	alert(count); //2 

	count = colors.push(“black”); 
	alert(count); //3 

	var item = colors.shift(); 		 			//get the first item
	alert(item); //”red” 
	alert(colors.length); //2

ECMAScript also provides an unshift() method for arrays. As the name indicates, unshift() does the opposite of shift(): it adds any number of items to the front of an array and returns the new array length. By using unshift() in combination with pop(), it’s possible to emulate a queue in the opposite direction

Reordering Methods

Two methods deal directly with the reordering of items already in the array: reverse() and sort().
the reverse() method simply reverses the order of items in an array. Take this code for example:

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

By default, the sort() method puts the items in ascending order — with the smallest value first and the largest value last. To do this, the sort() method calls the String() casting function on every item and then compares the strings to determine the correct order. This occurs even if all items in an array are numbers, as in this example:

	var values = [0, 1, 5, 10, 15]; 
	values.sort(); 
	alert(values); //0,1,10,15,5

Clearly, this is not an optimal solution in many cases, so the sort() method allows you to pass in a comparison function that indicates which value should come before which.
A comparison function accepts two arguments and returns a negative number if the first argument should come before the second, a zero if the arguments are equal, or a positive number if the first argument should come after the second

	function compare(value1, value2) { 
		if (value1 < value2) { return -1; 
		} 
		else if (value1 > value2) { 
			return 1; 
		} 
		else { 
		return 0; 
	} }
Manipulation Methods

There are various ways to work with the items already contained in an array. The concat() method, for instance, allows you to create a new array based on all of the items in the current array.This method begins by creating a copy of the array and then appending the method arguments to the end and returning the newly constructed array.

	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

The next method, slice(), creates an array that contains one or more items already contained in an array. The slice() method may accept one or two arguments: the starting and stopping positions of the items to return.

	var colors = [“red”, “green”, “blue”, “yellow”, “purple”]; 
	var colors2 = colors.slice(1); 
	var colors3 = colors.slice(1,4); 
	alert(colors2); //green,blue,yellow,purple 
	alert(colors3); //green,blue,yellow

Perhaps the most powerful array method is splice(), which can be used in a variety of ways. The main purpose of splice() is to insert items into the middle of an array, but there are three distinct ways of using this method. They are as follows:
➤ Deletion — Any number of items can be deleted from the array by specifying just two arguments: the position of the first item to delete and the number of items to delete. For example, splice(0, 2) deletes the first two items.

➤ Insertion — Items can be inserted into a specific position by providing three or more arguments: the starting position, 0 (the number of items to delete), and the item to insert. Optionally, you can specify a fourth parameter, fifth parameter, or any number of other parameters to insert. For example, splice(2, 0, “red”, “green”) inserts the strings “red” and “green” into the array at position 2.

➤ Replacement — Items can be inserted into a specific position while simultaneously deleting items, if you specify three arguments: the starting position, the number of items to delete, and any number of items to insert. The number of items to insert doesn’t have to match the number of items to delete. For example, splice(2, 1, “red”, “green”) deletes one item at position 2 and then inserts the strings “red” and “green” into the array at position 2.

	var colors = [“red”, “green”, “blue”]; 
	var removed = colors.splice(0,1); 	//remove the first item 
	alert(colors); 						//green,blue 
	alert(removed); 					//red - one item array 

	removed = colors.splice(1, 0, “yellow”, “orange”); //insert two items at position 1 
	alert(colors); 						//green,yellow,orange,blue 
	alert(removed); 					//empty array

	removed = colors.splice(1, 1, “red”, “purple”); 
	alert(colors); 						//green,red,purple,orange,blue 
	alert(removed); 					//yellow - one item array
Location Methods

ECMAScript 5 adds two item location methods to array instances: indexOf() and lastIndexOf().

	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 
Iterative Methods

ECMAScript 5 defines five iterative methods for arrays. Each of the methods accepts two arguments: a function to run on each item and an optional scope object in which to run the function (affecting the value of this). The function passed into one of these methods will receive three arguments: the array item value, the position of the item in the array, and the array object itself. Depending on the method, the results of this function’s execution may or may not affect the method’s return value:
– every() — Runs the given function on every item in the array and returns true if the function returns true for every item.
– filter() — Runs the given function on every item in the array and returns an array of all items for which the function returns true.
– forEach() — Runs the given function on every item in the array. This method has no return value.
– map() — Runs the given function on every item in the array and returns the result of each function call in an array.
– some() — Runs the given function on every item in the array and returns true if the function returns true for any one item.
//这里有一个很详细的范例,解释iterative method

//filter()
// The callback (anonymous function) is called once
// for each array element with 3 arguments. first one
// is the element itself. second one is the index of
// the element. 3rd one is the array itself.	
var nums = [1,2,3,4,5,6,7,8,9,10];
var res = nums.filter(function(element, index, array) {
		return element % 3 === 0;
	});
	logData(res); // [3,6,9]
===========================================================
// forEach() - just calls the provided callback
// once for each element in the array. It is
// really useful to iterate an array.
// the callback is called once per array element
// with 3 arguments similar to the previous example.but not return values

nums.forEach(function(element, index, array) {
     logData('nums['+index+'] = ' + element);
	});
-----Print Out ----
nums[0] = 1
nums[1] = 2
nums[2] = 3
nums[3] = 4
nums[4] = 5
nums[5] = 6
nums[6] = 7
nums[7] = 8
nums[8] = 9
nums[9] = 10




发表评论

Webmentions

  • Professional Javascript For Web Developers – 复习笔记 – Ian's Blog

    […] Language Basics (syntax,variable and operations) – Variables, Scope, And Memory – Reference Types – Array Type – Date Type – Regular Expressions […]

  • Professional Javascript For Web Developers – 复习笔记(Reference Types) | Ian's Blog

    […] The Arrary Type […]