P. 1
Mastering Javascript Arrays

Mastering Javascript Arrays

|Views: 4|Likes:
Published by nbsp

More info:

Published by: nbsp on Nov 07, 2010
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

08/28/2013

pdf

text

original

Mastering Javascript Arrays

By Patrick Hunlock 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.

Introduction
An 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]+', '); }

Which will output the following…
0, 1, 2, 3, 4, 5

Creating A New Array
Most tutorials start out introducing you to arrays as such…
var myArray = new Array(10);

Current best-practice eschews the new keyword on Javascript primitives. If you want to create a new Array simply use brackets [] like this…
var myArray = [];

Mastering Javascript Arrays

Page 1 of 25

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 new constructor avoids a bit of confusion where you want to initialize only one integer. For instance...
var badArray =new Array(10); // Creates an empty Array that's sized for 10 elements. var goodArray=[10]; // Creates an Array with 10 as the first element.

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 new Array() to create an Array.

Initializing An Array
You can initialize your array with predefined data…
var myArray = ['January', 'February', 'March']; document.writeln('0>'+myArray[0]+'<BR>'); document.writeln('1>'+myArray[1]+'<BR>'); document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 0>January // Will output: 1>February // Will output: 2>March

You can initialize your array with data after an empty array has been created…
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[2] = 'March'; document.writeln('0>'+myArray[0]+'<BR>'); // Will output: 0>January document.writeln('1>'+myArray[1]+'<BR>'); // Will output: 1>February document.writeln('2>'+myArray[2]+'<BR>'); // Will output: 2>March

If you skip an element, the blank Array elements will be of type undefined...
var myArray = []; myArray[0] = 'January'; myArray[1] = 'February'; myArray[5] = 'March'; document.writeln('0>'+myArray[0]+'<BR>'); document.writeln('1>'+myArray[1]+'<BR>'); document.writeln('2>'+myArray[2]+'<BR>'); document.writeln('3>'+myArray[3]+'<BR>'); document.writeln('4>'+myArray[4]+'<BR>'); document.writeln('5>'+myArray[5]+'<BR>');

// // // // // //

Will Will Will Will Will Will

output: output: output: output: output: output:

0>January 1>February 2>undefined 3>undefined 4>undefined 5>March

Mastering Javascript Arrays

Page 2 of 25

// Will output: 1>hello! document. var y=[x].color+'<BR>').writeln('2>'+myArray[2]()+'<BR>').3./[ell]/i ]. // Will output: 0.2.2. strings.2.4.writeln(bigArray[5][8][12][1]) …would indicate bigArray's 5th index held an array. // Will output: 3>blue document. who's first index contains the data we want.4.{'color':'blue'.'budget':25}.1.1.writeln('4>'+myArray[4].5 If we wanted the third index we'd access it this way… var x=[0.writeln('0>'+myArray[0]+'<BR>').'hello!'.1. document. who's 8th index held an array.4. ab Mastering Javascript Arrays Page 3 of 25 .writeln(y[0]).5].3.function() {return 5}. If we ask for the value of y[0] it will return the contents of x as a string because we didn't specify an index.writeln('1>'+myArray[1]+'<BR>').5]. For instance … document. even regular expressions… var myArray=[3. // Will output: 4>true Multi-Dimensional Arrays Since an Array can store other Arrays you can get the benefit of multi-dimension arrays. functions. document. var y=[x]. who's 12th index held an array. // Will output: 3>25 document. var x=[0.Storing Data In An Array An array can store anything you can assign to a variable: booleans. // Will output: 2 There's no defined limit to how many Arrays you can nest in this manner. document.1.3. numbers. // Will output: 0>3 document.5]. var x=[0. In the above example we created an array named x and assigned it as the first element in the array y.writeln('3>'+myArray[3].writeln(y[0][3]).4.2.writeln('3>'+myArray[3].test(myArray[1])+'<BR>'). var y=[x].3.budget+'<BR>'). // Will output: 2>5 document. other Arrays. objects.

For instance… var myArray = [ 'zero'. 'four'. 'four'.writeln(myArray[1]). 'three'. or as a pointer to the original. 'two'. // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'. } passedByReference(myArray). 'one'. // Will output: changed Javascript Arrays Are Assigned By Reference Assigning an Array to a new variable creates a pointer to the original Array. // Will output: one function passedByReference(refArray) { refArray[1] = 'changed'. 'three'.writeln(myArray[1]). use the Array. } passedByReference(myArray. // Will output: changed Passing Arrays As Values To pass an Array by value instead of by reference. 'two'.writeln(myArray[1]). document. 'four'. var myArray = [ 'zero'. newArray[1] = 'changed'. var newArray= myArray. 'five' ].Javascript Arrays Are Passed By Reference Arrays are passed to functions by reference. 'two'.slice()). 'one'.writeln(myArray[1]). var myArray = [ 'zero'. // Will output: one ab Mastering Javascript Arrays Page 4 of 25 .writeln(myArray[1]).slice(). 'one'. newArray[1] = 'changed'. document. This means anything you do to the Array inside the function affects the original.slice() method. document. 'five' ]. document. 'five' ]. 'three'. document. var newArray= myArray.

// Outputs: John Smith Javascript does not have.length). alert(normalArray[1]). Javascript Does Not Support Associative Arrays An associative array is an array which uses a string instead of a number as an index. so as long as our counter is less than the Array.length Every Array has a length property.writeln('0>'+myArray[0]+'<BR>'). just like . the length property is convenient for loops since it will always be one greater than the actual index. // Outputs: This is an enumerated array var associativeArray = []. Even though 3 of the Array items are undefined the length property will still count them because it's always one higher than the highest accessible index value.writeln('3>'+myArray[3]+'<BR>').writeln('2>'+myArray[2]+'<BR>'). i++) {} Going back to our undefined example above. For instance if the Array has 10 elements then the indexes will be 0-9. document. associativeArray['person'] = 'John Smith'. Since Arrays always start at zero. . normalArray[1] = 'This is an enumerated array'. i<myArray. . var myArray = []. myArray[5] = 'March'. creating 90 undefined elements after the original 10 items.Array. If you have 10 elements in an array and set Array. The 'person' element in the example becomes part of the Array object's properties and methods. document.sort(). Mastering Javascript Arrays Page 5 of 25 . and all the other built-in properties and methods.writeln('4>'+myArray[4]+'<BR>'). If you have 100 elements in an array and set the length to 50. myArray[1] = 'February'.length to 100 then the length of the array will be expanded to 100. myArray[0] = 'January'.writeln('5>'+myArray[5]+'<BR>').splice(). and does not support Associative Arrays.length. document. document. alert(associativeArray['person']).length.you can set it as you wish. This always contains the number of elements in the array. For this reason the example code above will actually work. document. Javascript will truncate the last 50 elements from the array (effectively deleting them). // // // // // // // Outputs Outputs Outputs Outputs Outputs Outputs Outputs 0>January 1>February 2>undefined 3>undefined 4>undefined 5>March Array Length: 6 Array.length we'll cover the entire Array… for (var i=0.length is NOT a read-only value -.writeln('1>'+myArray[1]+'<BR>'). document. var normalArray = []. However… All arrays in Javascript are objects and Javascript's object syntax gives a basic emulation of an associative Array. Be warned that this is not a real array and it has real pitfalls if you try to use it. document.writeln('Array Length: '+myArray.

ab Mastering Javascript Arrays Page 6 of 25 . an Object({}). associativeArray["two"] = "Second". // outputs: one:First. for (i in associativeArray) { document. A lot of problems people have with the Prototype framework is that their associative arrays break because Prototype adds a few useful functions to the global object and for i in x loops pick up those additional methods. The bottom line is -. or any other Javascript object.You can loop through an object's properties with the following syntax… var associativeArray = []. the previous code will work regardless of whether you define associativeArray as an Array ([]). Code for what they are -. In the above example.writeln(i+':'+associativeArray[i]+'. we put it into associativeArray's object. That's the pitfall of using Array/objects as a poor man's associative array. associativeArray[0] will be undefined. As a final example. a Regular Expression (//). associativeArray["one"] = "First". properties.object properties. two:Second.length will be zero because we didn't actually put anything into the Array.don't try to use associative arrays. associativeArray. '). not Arrays. String(""). The loop in the above example will also pick up any methods. three:Third }. and prototypes which have been added to the array and not just your data. associativeArray["three"] = "Third".

0 5. 3. 3.5 ** 3. unshift).5 Creates an array with each element which evaluates true in the function provided.5 5.0 Returns the last item in the Array and removes it from the Array. FF 1.5 Passes each element through the supplied function until true is returned. FF 1. pop) and queues (shift.0 5.0 Sorts the array alphabetically or by the supplied function. 4.0 Deletes the specified index(es) from the Array. * Prototype functions are available to make this method available to Internet Explorer and older browsers.Array Methods Reference Since Javascript Arrays are modified objects.5 Creates a new array with the result of calling the specified function on each element of the Array. 4. FF 1. FF 1. 3.0 * * * 5. returns the Array as a string.0 Joins all the Array elements together into a string. 4.5 4.0 * * * 3. FF 1.0 * 3.5 Searches the Array for specific elements.0 Joins multiple Arrays/Values. map pop push reverse shift slice some sort splice toSource toString unshift valueOf 4.0 Returns the Array as a string.0 Like toString. FF 1.0 4.5 3.0 Adds the item to the end of the Array.0 Returns the first item in the Array and removes it from the Array.0 Reverses the Array so the last item becomes the first and vice-versa.5 Returns the source code of the array.0 5. FF 1.5 3. Method concat every filter forEach join indexOf lastIndexOf IE Mozilla Notes Version Version 4. 4. 4.5 Calls a function for every element of the array until false is returned. ** Not supported. 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. each and every Array you create has a few core methods.5 Returns the last item in the Array which matches the search critera. Mastering Javascript Arrays Page 7 of 25 . FF 1. 3.0 Inserts the item(s) to the beginning of the Array.0 Returns a new array from the specified index and length.5 Executes a specified function on each element of an Array 3.

4.4.match(RegExp).]]) The concat method appends the passed values to the end of the Array.5.every(function) The every method is a Firefox method which accepts a function as an argument. var joinedArray=myArray.15]. // outputs: false This method can be prototyped to allow Internet Explorer and older browsers to use this method. var myArray = [1. var isNumeric = function(x) { // returns true if x is numeric and false if it is not.2.13.. This method will pass the current value.6].3].writeln(myArray. Simply copy the following code into your Javascript toolbox and the .concat(newArray.0 Array. var seven = 7.14.[object Object] Supported Since: Netscape 4.concat(value1[value2[value. eight. Every value of the array is passed to that function until the function returns false. the current index.'eight'. // outputs: true var myArray = [1.6. and a pointer to the array to your function -. nine).7. document.12. } var myArray = [1.3. var RegExp = /^(-)?(\d*)(\.every(isNumeric)). var nine = {'sky':'blue'. document. The values passed to the concat method can be anything you can assign to a variable in Javascript.4.12.2.5. If no elements return false then every will return true.?)(\d*)$/. It's a convenient way to test an Array and see if every element is a number for instance.0.5. // outputs: 1. curIndex.writeln(myArray). document.11.every(isNumeric)).Array.7. curArray).'ten'.8. seven.9. var newArray= [4.2.11. return String(x).10.writeln(myArray.7.5.writeln(joinedArray).13.. 'grass':'green'}. IE 4.2.2.15].3 document.3.14.6. passing back a NEW array containing the joined values.every() method will be available regardless of your browser version.myfunction(curValue. if an element returned false then every will return false. // outputs: 1.8.9.3. Mastering Javascript Arrays Page 8 of 25 . var eight = 'eight'.6.

In the Array. var thisp = arguments[1].prototype.7.5. we tested if the entire Array was composed of Numbers. if (typeof fun != "function") throw new TypeError().every() -. // outputs: 1. Internet Explorer: --- Array.'four'. document. var isNumeric = function(x) { // returns true if x is numeric and false if it is not.3. this[i].license if (!Array.call(thisp. this)) return false.5.//This prototype is provided by the Mozilla foundation and //is distributed under the MIT license.and if the element is a number it's placed in the new oddArray Array. } return true. curIndex.filter(isNumeric).org/pub/Linux/LICENSES/mit. Here we pass the array through the same function as .'six'. Mastering Javascript Arrays Page 9 of 25 . and a pointer to the array to your function -.every) { Array.9.filter() we can extract all the numbers.'two'.7.filter() method will be available regardless of your browser version.3. var RegExp = /^(-)?(\d*)(\.isNumeric -. curArray).every = function(fun /*.9 This method can be prototyped to allow Internet Explorer and older browsers to use this method.5. i++) { if (i in this && !fun. for (var i = 0.prototype. i < len. Simply copy the following code into your Javascript toolbox and the . thisp*/) { var len = this.length.writeln(oddArray).filter(function) Filter creates a new Array of items which evaluate to true in the supplied function. } var myArray = [1.myfunction(curValue. This method will pass the current value. }. i. the current index.'ten'].every() method. } Supported Since: Firefox 1. //http://www. var oddArray=myArray.match(RegExp). creating a new Array in the process. In Array.ibiblio.?)(\d*)$/. return String(x).'eight'.

//http://www.license if (!Array.filter) { Array.myfunction(curValue. curIndex. this)) res. if (typeof fun != "function") throw new TypeError(). Internet Explorer: --- Array. curArray). i++) { if (i in this) { var val = this[i]. }.'two'. and a pointer to the array to your function -. Simply copy the following code into your Javascript toolbox and the . Mastering Javascript Arrays Page 10 of 25 . 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.prototype. var printArray = function (x.writeln('['+idx+'] = '+x).3. i < len. All it does is pass each element of the Array to the passed function. idx) { document. i.prototype. It ignores any results from the function and it returns nothing itself.forEach(function) This is an odd little method.call(thisp.org/pub/Linux/LICENSES/mit. val.//This prototype is provided by the Mozilla foundation and //is distributed under the MIT license.push(val).length.5]. This method will pass the current value.'four'. } var myArray = [1. for (var i = 0. // outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5 This method can be prototyped to allow Internet Explorer and older browsers to use this method. } Supported Since: Firefox 1. } } return res.filter = function(fun /*. thisp*/) { var len = this.ibiblio. the current index. myArray. var thisp = arguments[1]. // in case fun mutates this if (fun. var res = new Array().forEach(printArray).5.forEach() method will be available regardless of your browser version.

two. //http://www. var test2 = myArray.length.'six'.call(thisp. 7.two.org/pub/Linux/LICENSES/mit.join('. // outputs: 1+two+3+four+5+six+7+eight+9+ten Supported Since: Netscape 3.9.'ten']. This is a very useful function if you need to convert an Array into something you can send back to the server.5.5. this[i]. Internet Explorer: 3. var test1 = myArray.ten document.join('+').ibiblio. for (var i = 0.writeln(test3+'<BR>').prototype. this). '). i++) { if (i in this) fun. 5.license if (!Array. var test3 = myArray. } }. six.0 ab Mastering Javascript Arrays Page 11 of 25 .//This prototype is provided by the Mozilla foundation and //is distributed under the MIT license. // outputs: 1.3.'four'. Internet Explorer: --- Array. i < len. } Supported Since: Firefox 1.5.join(delimeter) The join method will output your Array as a string with a delimiter of your choice.join(). thisp*/) { var len = this. 3.'eight'.7.six.writeln(test2+'<BR>'). Simply pick a unique delimiter which is not likely to appear inside the data in your Array then you can turn it back into an Array on the server side. if (typeof fun != "function") throw new TypeError().0. i.prototype. // outputs: 1. document. var myArray = [1.forEach) { Array.7. eight.eight.9. ten document. 9.3.'two'.writeln(test1+'<BR>'). var thisp = arguments[1].four. four.forEach = function(fun /*.

'eight'. startIndex]) The indexOf method will search the array until it matches your search criteria.push(index). // outputs: 5 document. var myArray = [1.find() method provided below in the useful prototypes section.'two'.license if (!Array.floor(from).writeln(myArray. } Supported Since: Firefox 1. index = array.prototype. from = (from < 0) ? Math.indexOf('six')).9. This method can be prototyped to allow Internet Explorer and older browsers to use this method. It will then return the index where the item was found.prototype.ceil(from) : Math.org/pub/Linux/LICENSES/mit.Array.7. for (.indexOf(element) while (index != -1) { foundItems.'ten'].indexOf(element.'six'.indexOf(searchStr[.5.indexOf) { Array. var index = array. from++) { if (from in this && this[from] === elt) return from. //http://www. from < len. Internet Explorer: --- Mastering Javascript Arrays Page 12 of 25 . //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license.5. from*/) { var len = this. ++index).'four'. var from = Number(arguments[1]) || 0. // outputs: -1 To find and return all occurrences of an item you can use the following code… var foundItems = []. It will match only one item and the match must be exact.3.indexOf() method will be available regardless of your browser version.indexOf('not here')). } return -1.length. } This will create an array of indexes which match your search criteria (element) and store them in foundItems[].indexOf = function(elt /*. This is not as useful as the custom . document. if (from < 0) from += len.ibiblio. }. Simply copy the following code into your Javascript toolbox and the .writeln(myArray.

'four'.ceil(from) : Math. } for (. }. startIndex]) Array. Simply copy the following code into your Javascript toolbox and the . lastIndexOf searches from last to first. //http://www. // outputs: 9 document.floor(from).5. if (from < 0) from += len.lastIndexOf) { Array. var from = Number(arguments[1]). } else { from = (from < 0) ? Math. //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license.lastIndexOf() method will be available regardless of your browser version.lastIndexOf = function(elt /*. var myArray = [1.Array.ibiblio.writeln(myArray.3.writeln(myArray.'six'. document. from--) { if (from in this && this[from] === elt) return from.9.'two'.5.7.1.lastIndexOf(searchStr[.prototype.lastIndexOf('not here')).org/pub/Linux/LICENSES/mit.indexOf() searches from first to last. Internet Explorer: --- Mastering Javascript Arrays Page 13 of 25 .lastIndexOf(5)).1. // outputs: -1 This method can be prototyped to allow Internet Explorer and older browsers to use this method. else if (from >= len) from = len .5. } Supported Since: Firefox 1.prototype.length.license if (!Array. from > -1. } return -1. from*/) { var len = this.'ten']. if (isNaN(from)) { from = len .'eight'.

'eight'. // outputs: 1. otherwise a zero is inserted. } else { return 0. } return res.map) { Array.map(function) The map method will call the provided function for each value of the array and it will return an array containing the results of those function calls.map() method will be available regardless of your browser version.5. if (typeof fun != "function") throw new TypeError(). this).?)(\d*)$/.'ten'].map = function(fun /*.'two'.5.0. var thisp = arguments[1]. var RegExp = /^(-)?(\d*)(\. this[i].license if (!Array. document.ibiblio.Array.0.prototype. i. the index.9. for (var i = 0.3.0 This method can be prototyped to allow Internet Explorer and older browsers to use this method.prototype. it's passed into the new array.org/pub/Linux/LICENSES/mit.length.7. } var testElement = function(x) { if (isNumeric(x)) { return x. and a pointer to the array being used respectively.match(RegExp).writeln(newArray). var newArray= myArray. Simply copy the following code into your Javascript toolbox and the .7.call(thisp.0. }. Internet Explorer: --- Mastering Javascript Arrays Page 14 of 25 .0.9. thisp*/) { var len = this. //http://www. i < len.'six'. return String(x).map(testElement). var isNumeric = function(x) { // returns true if x is numeric and false if it is not.'four'. if it is.5.3. i++) { if (i in this) res[i] = fun. var res = new Array(len). } } var myArray = [1. The callback function is called with three arguments: the value. In the following example each element of the array is tested to see if it is numeric. //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license. } Supported Since: Firefox 1.

4.5. myArray. // outputs: 1.5.3.5.7.5 // outputs: 5 // outputs: 1. var myArray = [1.6.3.writeln(popped+'<BR>'). In addition to being incredibly useful for adding items to the array.Array.1 Supported Since: Netscape 3. var myArray = [1. var myArray = [1.3.writeln(myArray+'<BR>'). document.3. myArray.8. document.2.4. document.writeln(myArray+'<BR>').0.2.7.8. value.push(7.9.6.9.4.writeln(myArray.9.7.8.10 // outputs: 10 Supported Since: Netscape 4.writeln(myArray+'<BR>'). Array.value2[.2.5.2.4.5. // outputs: 1. document.6.writeln(myArray.4.6.8.pop() The pop() method implements a basic stack structure in Javascript Arrays.4.4. // outputs: 9 Supported Since: Netscape 4.writeln(myArray+'<BR>').3. document.writeln(myArray+'<BR>'). Internet Explorer: 5. Internet Explorer: 5.9.5. // outputs: 10 var popped = myArray.2. document.length+'<BR>').3. myArray.3.9.reverse().9.6.push(value[.10].pop() will return the last element of an Array and delete it from the Array.0.10 document.4.3.6.5.10].length+'<BR>').3.7. document.2.4.8.push(6).length+'<BR>').2.]]) The push() method adds the passed value(s) to the end of the array. // outputs: 1.7. it also allows the Array to emulate a basic stack structure. document.8..10 // outputs: 10.7.6 // outputs: 6 // outputs: 1.writeln(myArray.length+'<BR>').writeln(myArray. document.7.2.10)..9 document.0 Mastering Javascript Arrays Page 15 of 25 . // outputs: 10 document.pop().4.length+'<BR>'). // outputs: 1.6.8.writeln(myArray.5 Array.3.0.5].reverse() The reverse() method takes the array and reverses the order so the first item becomes the last and the last item becomes the first.9.writeln(myArray+'<BR>').5.writeln(myArray+'<BR>').5 Array. Internet Explorer: 3.8.2. document.2.

6. var newArray = myArray.4. Shift implements a basic queue structure in Javascript Arrays.slice(5.3.8.7.4.3.writeln(theItem+'<BR>'). Internet Explorer: 4.5.4.9.slice([begin[.4. document.5.10 // outputs: 6. // outputs: 1.7. document. var newArray = myArray. document.writeln(newArray+'<BR>').7.slice(5).9. If you don't specify and ending index the splice will continue to the end of the Array.Array.6.0 Array.7.10]. So to make a copy of the array simply don't pass any arguments to the method.7.5. Together with Array. document.writeln(newArray+'<BR>').4. If you don't specify a beginning index the slice will begin at zero.9.10 Supported Since: Netscape 5.slice().writeln(myArray+'<BR>').3.8.10 // outputs: 1.5.9.5. end]]) The slice() method copies a block of the array and returns it to your new variable.8.shift() The shift() method returns the first item in the Array. document.9.2.6.3.5.8.writeln(newArray+'<BR>').shift().writeln(myArray+'<BR>').0 ab Mastering Javascript Arrays Page 16 of 25 .2.2.8.4.10].10 // outputs: 1 // outputs: 2.6. // outputs: 1.10 // outputs: 6. var myArray = [1.7).6.6.0.7.3. document.9.3. theItem = myArray.7 Supported Since: Netscape 4.9.7. removing it from the Array in the process. var newArray = myArray. Internet Explorer: 4.2.unshift.5. document.2. var myArray = [1.8.writeln(myArray+'<BR>').8.

i++) { if (i in this && fun. for (var i = 0.ibiblio. // outputs: false var myArray = ['one'. If the entire array has been traversed and no true condition was found then some() will return false. return String(x). 'five']. i. } return false. 'four'. i < len. Simply copy the following code into your Javascript toolbox and the .prototype. //This prototype is provided by the Mozilla foundation and //is distributed under the MIT license.5.license if (!Array.match(RegExp).writeln(myArray. 'five'].org/pub/Linux/LICENSES/mit. this)) return true. 'two'. // outputs: true This method can be prototyped to allow Internet Explorer and older browsers to use this method. var RegExp = /^(-)?(\d*)(\. }.call(thisp. thisp*/) { var len = this. } Supported Since: Firefox 1.some(isNumeric)).some) { Array. document.some() method will be available regardless of your browser version.?)(\d*)$/. 3. if (typeof fun != "function") throw new TypeError(). Internet Explorer: --- ab Mastering Javascript Arrays Page 17 of 25 . document.some(function) The some() method will pass each element of the Array through the supplied function until true has been returned. var thisp = arguments[1].Array. 'two'. 'four'.length.some = function(fun /*. 'three'.some(isNumeric)).prototype. If the function returns true some will in turn return true. } var myArray = ['one'. this[i]. //http://www.writeln(myArray. var isNumeric = function(x) { // returns true if x is numeric and false if it is not.

supply a function for the sort method to call. // Sort Numerically document.19.0.7.7. If you would like to create your own sorting criteria. var myArray=[8.24. myArray.24.50. // 10.sort( function (a.Array. Supported Since: Netscape 3.b).10.8.8.5.83.writeln(myArray). //5. Internet Explorer: 3. b) { // psudeo code. If a is less than b then return -1.10.b) { return a-b }).50.168 function compare(a.83. Sort will take it from there. by default. will sort an Array alphabetically.writeln(myArray).sort() document.168]. if a is equal to b then return 0.19.50. if (a < b) { return -1.sort([function]) The sort() method.24. if a is greater than b then return 1.168.19. } } myArray. } if (a > b) { return 1.0 ab Mastering Javascript Arrays Page 18 of 25 .7.sort(compare).5.83 (sorted alphabetically) myArray. Sort will pass your function (a. } if (a == b) { return 0.

myArray=[1.5. document. // outputs 6 //truncate the array at the 5th index.5.4. document. element1[.9 // Insert without deleting.9.3.4.10 document.2. and 'green' myArray=[1.4.2.7.splice(4.7..10 Supported Since: Netscape 4.writeln(myArray). // outputs: 1.9. // outputs undefined // cut out the middle and insert 'blue'.5.4.7.8.8. // outputs 2.Array.2. Internet Explorer: 5.3.8.5. newArray = myArray. newArray = myArray.element. splice will truncate the array.6.3. If you specify a starting number but don't specify how many.10]. //delete one item at the 5th index.4.6.9.4.5 Mastering Javascript Arrays Page 19 of 25 .10].writeln(newArray).10].2. // outputs: 1.10].10 // do nothing at all.8.splice(start[. document.0.6.4.3.3. // outputs: 1. var myArray=[1.7.writeln(newArray).]]]) The splice() method at it's most basic allows you to delete an element from the array by simply specifying the index you'd like to delete and then how many elements you'd like to delete from that point.3.5.splice(1.writeln(newArray).6.9. 'blue'.5.6.3. newArray = myArray.5. '*').*.9.9.8.10].writeln(myArray). You can insert elements into the array without deleting anything by specifying zero for howmany..7.2.2. myArray=[1.10 document. // outputs 6.1). // outputs: 1.7. howmany[. newArray = myArray.2.2.4.splice().5.green.7.3.3. document.4.9. '*').blue. // outputs: 1.*.2.5.0. myArray=[1.0.3.7. splice() returns a new array containing the removed items.10 document.6.writeln(myArray). You can also specify any number of elements to insert into the array at that point.6.9.7.8.8.splice(5.8. document.4.7.splice(5.splice(5). 'green').writeln(myArray).8.8.9.writeln(newArray). newArray = myArray.5 document.writeln(myArray). newArray = myArray.6. var newArray=[].8.

"c". document.. it works only in Firefox. var myArray = ["a".toString(). document.6.9. This is a useful debugging method and can be useful in Ajax/JSON applications. if you were to use the toSource() method and pass it through an eval statement you could rebuild the array. Supported Since: Firefox 1.toSource() The toSource() method is a Firefox only extension which takes the contents of an Array and returns the source code. Internet Explorer: 4. {'sky':'blue'.[object Object] Supported Since: Netscape 3.7. var myArray = [1. value2[.toString() document. "b".7.1. "b".10]. Together with the shift(). var theSource = myArray.writeln(theSource).writeln(myArray+'<BR>').2. "c".10 Supported Since: Netscape 5. {'sky':'blue'. 'grass':'green'}].4.8.4. It's not as powerful as toSource() since it doesn't expand objects but it is supported by browsers other than Firefox.0.8.9.4. Mastering Javascript Arrays Page 20 of 25 .b..5. // outputs: ["a". // outputs: 1.2.5.3. var theSource = myArray. Internet Explorer: 3.5. var myArray = ["a".0 Array. myArray.b.8.toString() This method outputs the contents of the Array as a string. That is.c.10 // outputs: a.writeln(myArray+'<BR>').3. value.'b'.2. grass:"green"}] {sky:"blue".5. Internet Explorer: --- Array.'c').unshift('a'. "c".6.toSource() document. unshift() implements a basic queue structure in Javascript Arrays.6.9.unshift(value1[. // outputs: a. There is no prototype for this method.7. "b".valueOf() See Array.0 Array.]]) The unshift method inserts the value(s) passed in the method's arguments into the start of the Array.3.writeln(theSource). 'grass':'green'}].Array.5.c.

it's actually not that easy to differentiate an Array and an Object.6.2.1).7. // clear-out the array document.propertyIsEnumerable('length')) && typeof testObject === 'object' && typeof testObject. So here's a little function that will let you ask the array itself what it is. even when you absolutely need to.30.2.30]. Howto Tell The Difference Between An Array And An Object Because Javascript's Array is just a modified Javascript object.35.10 myArray = [].18.2.8.12.5. // outputs: 1.3. var tmp2 = {0:5. Mastering Javascript Arrays Page 21 of 25 .1:9. isArray() will return true if it's an array and false if it is not an Array.27.3.7.6.4.5.8. document.4.9. var myArray=[1.9.9. var myArray=[1. var myArray=[1. // returns false.97.splice(5.3. // outputs: 1.2:12} test1 = isArray(tmp). delete myArray[3].4.9.2.53.9.10].33. myArray. } Usage… var tmp = [5.2.length === 'number'.3.2.4.10].8.7. // outputs null Alternatively you can set the length of the array to zero ( myArray.Howto Delete An Element From An Array You can delete an item from an Array with the splice() method.6.writeln(myArray).writeln(myArray).length=0).8.10 You if you would like to unset an element use the delete operator.'blue'.writeln(myArray). function isArray(testObject) { return testObject && !(testObject.4. // returns true test2 = isArray(tmp2).undefined.5]. likewise if you just need to clear out a few items at the end of the array.writeln(myArray). //delete one item at the 5th index.5 You can also use the pop() method to remove items from the end of the array and the shift() method to remove items from the beginning of the array.5.30. // outputs: 1. document.3.7. Simply supply the index of the item you wish to delete and how many items you want to delete and the item(s) will be removed for you. Howto Clear-out/Reset An Array Clearing out or resetting an array is as simple as assigning it a new empty bracket. lower the length property by the number of items you would like removed from the end of the array.5.7.4. document.

length). myArray[0] = 'January'. // theData=1~2~3~4~5~6~7~8~9~10 theData=encodeURIComponent(theData).writeln('2>'+myArray[2]+'<BR>').length property. // Adds Item to end of Array document.2.5.unshift('January').length] = 'March'. This will add the requested items to the end of the Array. Find a unique character that is unlikely to appear inside your Array and use it as your delimiter. // Will output: // Adds Item to // Will output: // Will // Will // Will 2 end of Array 3 output: 0>January output: 1>February output: 2>March You can add the .writeln(myArray.6. var myArray = []. // Will output: 0>January document.8. Since Arrays start with index 0. myArray[myArray.3. // Will output: 2>March You can use the . myArray[1] = 'February'.writeln('1>'+myArray[1]+'<BR>'). myArray[1] = 'March'. document. then Array. myArray.length is always equal to the first empty index at the end of the Array. var theData = myArray.push() method of the Array. // Will output: 1>February document.4.unshift() method to insert an item at the BEGINNING of the array! var myArray = []. myArray.writeln('0>'+myArray[0]+'<BR>'). Mastering Javascript Arrays Page 22 of 25 . myArray[0] = 'February'.writeln('0>'+myArray[0]+'<BR>'). document. // Will output: 1>February document. // Will output: 0>January document. document. you need to use the join method to turn your Array into a string.7. For most applications the tilde (~) character is a safe decimeter to use.writeln('2>'+myArray[2]+'<BR>').writeln('1>'+myArray[1]+'<BR>'). var myArray = [].9.Howto Easily Add Items To An Array There are three ways to easily add items to an array.join('~').10].push('March'). // Adds Item to beginning of Array document. myArray[1] = 'February'. On the server just do a split('~') in PhP to turn it back into an Array.length). // Optional but safe! Escape the data Now just send theData through your Ajax routine. First you can use the Array.writeln('2>'+myArray[2]+'<BR>').writeln('1>'+myArray[1]+'<BR>'). myArray[0] = 'January'. var myArray=[1. document.writeln('0>'+myArray[0]+'<BR>'). // Will output: 2>March Howto Pass An Array Via Ajax If you have an Array you need to package up and send via Ajax. document.writeln(myArray.

Array.50. Useful Prototypes: Array. Once you've received the string from your Ajax handler simply use the string's split method to bust the string into an Array.2.10 Useful Prototypes With prototypes you can extend the Array object and include any additional functionality you wish.split('~'). even arrays that haven't been assigned to variables… document.12. Any array can access it. var ajaxStr = '1~2~3~4~5~6~7~8~9~10'.80.writeln(myArray).12.6. For instance. However.3. (We're assuming a string with a tilde [~] delimiter in this example). just use the sortNum() method when you want to sort an array numerically instead of alphabetically. } ).8.9. there are a few snippets people have found helpful.b) { return a-b.8.7. } ).implode in PhP.sortNum() As stated above.sortNum()).80.sortNum = function() { return this.sortNum = function() { return this. } All this does is make sortNum a method of Array just like sort and splice and join and all the other default methods.5.25.prototype.4.8.writeln([5. } ab Mastering Javascript Arrays Page 23 of 25 .b) { return a-b. // outputs: 1. there's not much left that needs to be done.93].50. document. the Array.sort( function (a.Howto Receive An Array Via Ajax On the server side convert the Array into a string using a unique delimiter -.93 Since the Javascript Array object is already so rich.25. var myArray = ajaxStr.sort() method sorts alphabetically by default but adding a numerical sort is as simple as including the following snippet of code in your toolbox. // outputs 5.sort( function (a.prototype. Array.

13.find(35).shuffle = function (){ for(var rnd.30. First it will return an array of all the indexes it found (it will return false if it doesn't find anything).find('not there!').6.find(30).15].push(i). i++) { if (typeof(searchStr) == 'function') { if (searchStr.15.27. this shuffle() method will take the contents of the array and randomize them.find('35').11.19.56. } } else { if (this[i]===searchStr) { if (!returnArray) { returnArray = [] } returnArray.9.shuffle().20 (first letter starts with b) regexp1=tmp.'blue'. // outputs~: 8.6.18. This method is surprisingly useful and not just for shuffling an array of virtual cards. i=this.push(i). Usage… var myArray = [1. Array.10. myArray. this[rnd]=tmp).7. this[i]=this[rnd]. tmp=this[-i].5.test(this[i])) { if (!returnArray) { returnArray = [] } returnArray.10.33. which makes this the ultimate Array prototype in my book. 14.10.8.prototype.7. } Usage… var // var var var var var var var tmp = [5.'35'.12.20 (same as above but ignore case) Useful Prototypes: Array.14.5.4.9. // Returns 15 haveBlue=tmp.42.13.11.97.find('blue').indexOf() is a nice method but this extension is a little more powerful and flexible. // Returns 18 thirtyfive=tmp.30.writeln(myArray). i.length.1.length. }.find(/^b/i).1. rnd=parseInt(Math.prototype. 7.2.12.4.53.find = function(searchStr) { var returnArray = false.find(searchStr) Array.35.'Ball'.14.Useful Prototypes: Array.3. 17 thirtyfive=tmp. tmp.find(/^b/). // Returns false regexp1=tmp.9 Mastering Javascript Arrays Page 24 of 25 .3.shuffle() The anti-sort.30.2. } } } return returnArray. // Returns 9. for (i=0.random()*i). // returns 8. i<this. // returns 8. Array. 'bubble']. // Returns 8 notFound=tmp. 0/1/2 /3 /4/5 /6 /7 /8 /9/10/11/12/13/14/15/16/17/ 18/ 19/ 20 thirty=tmp. Second in addition to passing the usual string or number to look for you can actually pass a regular expression.12. document.

12.8.writeln(myArray.compare(yourArray)).4.14.11.6.3. } if (this[i] !== testArr[i]) return false.hunlock.compare(array) If you need to be able to compare Arrays this is the prototype to do it.compare(yourArray)).6. Version This document is current as of Firefox 2. i < testArr.13.Useful Prototypes: Array.7 License Copyright © 2007 by Patrick Hunlock – http://www. Pass an Array you want to compare and if they are identical the method will return true.length) return false.10. document.compare) { if (!this[i].15]. for (var i = 0. If there's a difference it will return false.7. var yourArray = [1.writeln(myArray. true.compare(yourArray)).9. // outputs: yourArray[0]=1. The source codes (but not the article itself) in this document are released into the public domain and may be used without compensation or attribution.15].com.12. i++) { if (this[i].prototype.8.4.7.0.3.10. false.5. // outputs: yourArray[0]='1'. } return true. ECMA-262 Edition 3. } Usage… var myArray = [1. document.writeln(myArray.2.6.5.2. // outputs: true.03.11. Array. IE 7. The match must be identical so '80' is not the same as 80.compare(testArr[i])) return false.compare = function(testArr) { if (this.compare(yourArray)). Javascript 1. Mastering Javascript Arrays Page 25 of 25 . document. document.13. JSCRIPT 5.length.writeln(myArray.9.length != testArr. // outputs: yourArray[0]='one'.14. false.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->