04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 22: The Evolution of JavaScript<br />

The code in this example returns an array containing the result of multiplying each number by two. This<br />

method is helpful when creating arrays whose items correspond to one another.<br />

The last method is forEach() , which simply runs the given function on every item in an array. There is<br />

no return value and is essentially the same as iterating over an array using a for loop. Here’s an example :<br />

var numbers = [1,2,3,4,5,4,3,2,1];<br />

numbers.forEach(function(item, index, array){<br />

//do something here<br />

});<br />

All of these array methods ease the processing of arrays by performing a number of different operations.<br />

The array extras are supported in Chrome, Firefox, Safari 3 and later, and Opera 9.5 and later.<br />

Array and String Generics<br />

A technique introduced earlier in this book used Array.prototype.slice() to create an array out of<br />

the arguments object as shown here:<br />

var args = Array.prototype.slice.call(arguments);<br />

This works because the arguments object is array - like, so it can be passed in as the scope object for the<br />

method. JavaScript 1.6 introduces generic versions of all array and string methods attached to the Array<br />

and String objects. Generic methods expect the first argument to be the object on which to act, and the<br />

other arguments are the same as the instance arguments. For example, the previous code can be<br />

rewritten like this:<br />

var args = Array.slice(arguments);<br />

You can even sort an arguments object without creating an array, like this:<br />

Array.sort(arguments);<br />

Or add a new argument, like this:<br />

Array.push(arguments, “red”);<br />

The same can be done with all string methods. As with the array generic methods, string generic<br />

methods need not be used only on strings. If a different data type is passed in, it is converted into a<br />

string, the operation is performed, and the result is returned as a string, as in this example:<br />

//credit: http://developer.mozilla.org/en/docs/New_in_JavaScript_1.6<br />

var num = 15;<br />

alert(String.replace(num, /5/, “2”)); //”12”<br />

This code produces the string “ 12 ” by converting num into a string and then calling replace() on it.<br />

Array and string generics eliminate the need for explicit data type conversions before working<br />

with values, as well as eliminating the need to access methods on Array.prototype and<br />

String.prototype when used on different data types. Generics are supported in Firefox 1.5 and later.<br />

708

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!