|
網誌存檔
熱門網志
|
|
Mastering Javascript ArraysFiled: Sun, Mar 25 2007 under Programming|| Tags: reference arrays javascript stacks queues ajax Mastering Javascript Arrays Believe it or not, the very first version of Javascript shipped without Arrays. Subsequent versions made up for the oversight and modern Javascript Arrays are powerful structures indeed, even emulating many common data structures such as stacks and queues. This reference will cover the core functionality of Arrays as well as introduce a few useful extensions. IntroductionAn Array is an enumerated list of variables. It`s a programming construct that allows programmers to replace this… x0=0;x1=1;x2=2;x3=3;x4=4;x5=5; …with this… x[0]=0;x[1]=1;x[2]=2;x[3]=3;x[4]=4;x[5]=5; The index (the number in the brackets [] )can be referenced by a variable, allowing for easy looping through the data structure. for(i=0; i<6; i++) { document.writeln(x[i]+`<br>); }Which will output the following… 012345 Creating A New ArrayMost tutorials start out introducing you to arrays as such… var myArray = new Array(10); Current best-practice eschews the var myArray = []; You don`t need to tell Javascript how many items to size the Array for. Javascript will automatically increase the size of the Array as needed, as you add items into the Array. Creating an Array with brackets instead of with the var badArray = new Array(10); // Creates an empty Array that`s sized for 10 elements. As you can see these two lines do two very different things. If you had wanted to add more than one item then badArray would be initialized correctly since Javascript would then be smart enough to know that you were initializing the array instead of stating how many elements you wanted to add. Since the new constructor is not necessary with Arrays and there`s a slight chance of unintended results by using the new constructor, it`s recommended you not use Initializing An ArrayYou can initialize your array with pre-defined data… var myArray = [`January`, `February`, `March`]; You can inizialize your array with data after an empty array has been created… var myArray = []; If you skip an element, the var myArray = []; Storing Data In An ArrayAn array can store anything you can assign to a variable: booleans, numbers, strings, functions, objects, other Arrays, even regular expressions… var myArray = [ 3, `hello!`, function() {return 5}, {`color`:`blue`, `budget`:25}, /[ell]/i ]; Multi-Dimensional ArraysSince an Array can store other Arrays you can get the benefit of multi-dimension arrays. var x=[0,1,2,3,4,5]; In the above example we created an array named var x=[0,1,2,3,4,5]; If we wanted the third index we`d access it this way… var x=[0,1,2,3,4,5]; There`s no defined limit to how many Arrays you can nest in this manner. For instance … document.writeln(bigArray[5][8][12][1]) …would indicate bigArray`s 5th index held an array, who`s 8th index held an array, who`s 12th index held an array, who`s first index contains the data we want. Javascript Arrays Are Passed By ReferenceArrays are passed to functions by reference, or as a pointer to the original. This means anything you do to the Array inside the function affects the original. var myArray = [ `zero`, `one`, `two`, `three`, `four`, `five` ]; Javascript Arrays Are Assigned By ReferenceAssigning an Array to a new variable creates a pointer to the original Array. For instance… var myArray = [ `zero`, `one`, `two`, `three`, `four`, `five` ]; Passing Arrays As ValuesTo pass an Array by value instead of by reference, use the Array.slice() method. var myArray = [ `zero`, `one`, `two`, `three`, `four`, `five` ]; Array.lengthEvery Array has a for (var i=0; i<myArray.length; i++) {} Going back to our var myArray = []; Array.length is NOT a read-only value, you can set it as you wish. If you have 100 elements in an array and set the length to 50, Javascript will truncate the last 50 elements from the array (effectively deleting them). If you have 10 elements in an array and set Array.length to 100 then the length of the array will be expanded to 100, creating 90 undefined elements after the original 10 items. Javascript Does Not Support Associative ArraysAn associative array is an array which uses a string instead of a number as an index. var normalArray = []; Javascript does not have, and does not support Associative Arrays. However… All arrays in Javascript are objects and Javascript`s object syntax gives a basic emulation of an associative Array. For this reason the example code above will actually work. Be warned that this is not a real array and it has real pitfals if you try to use it. The `person` element in the example becomes part of the Array object`s properties and methods, just like .length, .sort(), .splice(), and all the other built-in properties and methods. You can loop through an object`s properties with the following loop… var associativeArray = []; In the above example, associativeArray.length will be zero because we didn`t actually put anything into the Array, we put it into associativeArray`s object. The loop in the above example will also pick up any methods, properties, and prototypes which have been added to the array and not just your data. A lot of problems people have with the Prototype library is that their As a final example, the previous code will The bottom line is -- don`t try to use associative arrays, code for what they are -- object properties, not Arrays. Array Methods ReferenceSince Javascript Arrays are modified objects, each and every Array you create has a few core methods. What`s really interesting is that some of these methods implement basic data structures you`d normally have to write yourself such as stacks (push, pop) and queues (shift, unshift).
* Prototype functions are available to make this method available to Internet Explorer and older browsers. Array.concat(value1[value2[value...]])The concat method appends the passed values to the end of the Array, passing back a NEW array containing the joined values. The values passed to the concat method can be anything you can assign to a variable in Javascript. var myArray = [1,2,3]; Supported Since: Netscape 4.0, IE 4.0 Array.every(function)The every method is a Firefox method which accepts a function as an argument. Every value of the array is passed to that function until the function returns false. If no elements return false then every will return true, if an element returned false then every will return false. It`s a convenient way to test an Array and see if every element is a number for instance. This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray) var isNumeric = function(x) { This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .every() method will be available regardless of your browser version. //This prototype is provided by the Mozilla foundation and Supported Since: Firefox 1.5, Internet Explorer: --- Array.filter(function)Filter creates a new Array of items which evaluate to true in the supplied function. In the Array.every() method, we tested if the entire Array was composed of Numbers. In Array.filter() we can extract all the numbers, creating a new Array in the process. This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray) Here we pass the array through the same function as .every() -- isNumeric -- and if the element is a number it`s placed in the new var isNumeric = function(x) { This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .filter() method will be available regardless of your browser version. //This prototype is provided by the Mozilla foundation and Supported Since: Firefox 1.5, Internet Explorer: --- Array.forEach(function)This is an odd little method. All it does is pass each element of the Array to the passed function. It ignores any results from the function and it returns nothing itself. It will pass all the Array contents through the function of your choice but the Array itself will not be affected and it will return nothing by itself. This method will pass the current value, the current index, and a pointer to the array to your function. myfunction(curValue, curIndex, curArray) var printArray = function (x, idx) { This method can be prototyped to allow Internet Explorer and older browsers to use this method. Simply copy the following code into your Javascript toolbox and the .forEach() method will be available regardless of your browser version. //This prototype is provided by the Mozilla foundation and |
-------------------------------------------------
| 上一篇:The Complete Javascript Strings Reference | 下一篇:Functional Javascript |

