ES5 one of the new functions: Array, JSON, String, Date

Source: Internet
Author: User

ES5, ECMAScript 5.1, adds a lot of new features on top of the JavaScript language to enhance and standardize existing objects and statements, including some new functions, object type enhancements, and strict schema programming specifications.

Today we will introduce the following new functions:

Array.isarray (obj);

Array.prototype.forEach ();

Array.prototype.indexOf ();

Array.prototype.lastIndexOf ();

Array.prototype.filter ();

Array.prototype.map ();

Array.prototype.some ();

Array.prototype.every ();

Array.prototype.reduce ();

Json.parse ();

Json.stringify ();

String.prototype.trim ();

Date.now ();

Date.prototype.toISOString ();


Let's describe their usage:

Array.isarray (obj);

It is obvious that this function is used to determine whether an object is an array type, if it is true, otherwise returns false, we can test the function with a simple array:

var arr = [1, 2, 3, 4, 5];var func = function () {};console.log (' is arr the Array type? ', Array.isarray (arr)); Console.log (' is func the Array type? ', Array.isarray (func));

Execute the above code, and the console prints as shown:


We can easily implement our own version of the IsArray function:

Array.isarray = Array.isarray | | function (obj) {return Object.prototype.toString.call (obj) = = = ' [Object Array] ';};


Array.prototype.forEach ();

The foreach function is a function defined on the array prototype to implement the most basic array traversal operations, so we can invoke the implementation traversal directly above the array:
Console.group (' For each are running '); [1, 2, 3, 4, 5].foreach (function (item, index, array) {Console.log (' The current index was: ' + index + ', value is: ' + item );}); Console.groupend ();

In the callback function, the first two parameters represent the current element and index, the last parameter is the array itself, when printing we use the console group and GroupEnd to group the results of the console, the code executes, the results are printed as follows:



Array.prototype.indexOf (); & Array.prototype.lastIndexOf ();

These two functions are used to get the index of the first occurrence and last occurrence of the specified element in the array, using the following method:

var arr = [1, 2, 3, 4, 5, 3];//indexofvar indexOf3 = Arr.indexof (3); Console.log (' The index of 3 in the array: ', INDEXOF3) ;//lastindexofvar lastIndexOf3 = Arr.lastindexof (3); Console.log (' The last index of 3 in the array: ', lastIndexOf3);

The two functions can also pass a second optional parameter, which indicates that the lookup starts at the specified index. The above code prints the following results:


Array.prototype.filter ();

The filter function filters the original array one time based on the filtering rules specified by the callback function, and returns a new array containing the array elements that match the filter criteria. For example, if we want to filter out all the odd elements from an array, we can use the filter function to easily implement:

var Oddarr = [1, 2, 3, 4, 5].filter (function (item) {Return item% 2!== 0;}); Console.log (' afer filter called, got a new array with odd numbers: ', Oddarr);
The above code results are printed as follows:


Array.prototype.map ();
The map function returns a new array that, based on the calculation rules for the original array elements in the callback function, maps the results of each element to the corresponding position of the new array, which is equivalent to the mapping of a computed map for the whole of the array, and we use the following simple code to explain the operation:

var Doublearr = [1, 2, 3, 4, 5].map (function (item) {return item * 2;}); Console.log (' After map called, got a new array with double numbers: ', Doublearr);
As shown in the code above, we want to make each element of the original array twice times the original, use the map function, get to a new array, each element in the new array and the corresponding elements of the original array has twice times the relationship, we can look at the console's printing results:



Array.prototype.some ();

The some function returns true if some elements within the array satisfy the decision rule for the specified callback function, or False if no element satisfies the rule. For example, in the following code we can determine if there are some elements greater than 3 in the array:

var someoneGreaterThan3 = [1, 2, 3, 4, 5].some (function (item) {return item > 3;}); Console.log (' There some elements in the array which is greater than 3? ', SOMEONEGREATERTHAN3);
Because there are more than 3 elements in the array, the call to the some function expects to return a true, so let's look at the print results:


Array.prototype.every ();

Every, like some, returns TRUE or FALSE, except that every returns true only if all elements within the array satisfy the criteria, otherwise false. or using the same array, let's make two judgments:

var arr = [1, 2, 3, 4, 5];var everyoneGreaterThan0 = arr.every (function (item) {return item > 0;}); Console.log (' is, ' all elements be greater than 0? ', everyoneGreaterThan0); var everyoneGreaterThan3 = arr.every (function (item) {return item > 3;}); Console.log (' is, ' all elements be greater than 3? ', EVERYONEGREATERTHAN3);
In the above code we call two times every function, determine whether all elements are greater than 0, whether all elements are greater than 3. According to our own judgment, you should return True and false, respectively, to the print result:


Array.prototype.reduce ();
In this series of functions, the reduce function is the most complicated one, whether its name or computational logic, the first contact is more difficult to understand. Reduce here means "degradation" or "protocol", is a process to transform a complex result set into a simple result, the function signature is as follows:

Arr.reduce (callback[, InitialValue])
We can see that the reduce function contains two parameters, the callback function callback and the initial computed value initialvalue, the initial calculated value is an optional parameter, if this parameter is specified, will participate in the operation the first time the callback is called, There are three parameters in the callback function:

Previouscalculatedvalue: The return value of the result after the last operation, the result will participate in the next operation as the new initial value, if InitialValue is specified, the first operation is Previouscalculatedvalue is the value of InitialValue, and if InitialValue is not specified, the first operation, Previouscalculatedvalue, is the value of the first element of the array.

CurrentItem: The element in the array that is currently participating in the operation.

Array: Call reduce on the arrays object itself.

Let's take a simple example to illustrate the specific computational process of reduce, for example, we have an array that wants to require all the elements in and out of a group, and so it can be called:

var sum = [1, 2, 3, 4, 5].reduce (function (Previouscalculatedvalue, CurrentItem, index, array) {var currentsum = Previousca Lculatedvalue + currentitem;console.log (previouscalculatedvalue + ' + ' + currentitem + ' + ' + currentsum); return CU Rrentsum;}); Console.log (' The sum of all elements in the array: ', sum);
Let's take a look at the printing information:

We can clearly see how each step is calculated, the first operation, the initial value is the first element of the array, and the current value is the second element of the array, the operation is complete, the result of the operation as the initial value of the next round operation, start a new round of operations, until the last element of the array to participate in the operation, The process of the entire statute ends, and the result of the operation is returned. Before we introduce the optional parameter initialvalue, if you specify this parameter, the program uses this initial value for the first operation, and the current element starts with the first element in the array, one step more than the previous procedure. Let's change the code a little bit to verify that:

var sum = [1, 2, 3, 4, 5].reduce (function (Previouscalculatedvalue, CurrentItem, index, array) {var currentsum = Previousca Lculatedvalue + currentitem;console.log (previouscalculatedvalue + ' + ' + currentitem + ' + ' + currentsum); return CU Rrentsum;}, 0); Console.log (' The sum of all elements in the array: ', sum);
We have added an initial value of 0, without affecting the result of the operation, to see how it works:

I believe from the results of this operation, we have seen the clues in the course of it.
Our example above is relatively simple, in fact, reduce can do a lot of complicated operations, for example, we have a two-dimensional array, we need to degrade it into a simple array, you can call reduce easy to implement:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce (function (Previousvalue, CurrentItem) {Console.log (Previousvalue, Currenti TEM);  Return Previousvalue.concat (CurrentItem);}, []) Console.log (' after reduce called on a two-dimensional array, the result I S: ', flattened);
Let's also look at the running process and the results:


In addition to the reduce, there is a function similar to it, it is reduceright, the only difference is that its operation direction from the end of the array, you can test it yourself.

The above is the array part of the new function, in the development is still very helpful, if you want to understand the operation of an array, you can move to the introduction of an array in the MDN page, in the relevant new function introduction, there are corresponding polyfill, for the lower version of the browser to provide support for these functions. Here's the Mozilla MDN page:

Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

The above is the array section, and let's introduce the new functions of several other classes:


Json

JSON (JavaScript object Notation) is a lightweight data interchange format that is used in development to build data that is easy to read and write, and that uses two structures: objects and arrays.

In the past, when we used JSON data, we used to transform it with a third-party library, and with the release of ES5, the new standard built-in JSON objects for conversion between JSON objects and JSON strings. JSON as a global object, we can call directly, it has the following two functions:

Json.parse (string);//is responsible for converting the string to a Josn object and returning the Json.stringify (data),//is responsible for converting it to a JSON string and returning, data can be null, Boolean, number, String, Jsonobject, Jsonarray
Let's use an example to explain the use of these two functions:
var person = {  id:1,  name: ' Scott ',  Hobbies: [' basketball ', ' Pingpang ', ' music ']};var personstring = json.st Ringify (person); Console.log (personstring); var Newperson = Json.parse (personstring); Console.log (Newperson);

The printing results are as follows:

String.prototype.trim ();

ES5 also added a useful function for the string class, the trim () function, to remove extraneous whitespace before and after the string, a method that has brought great convenience to the developer in the jquery era, and it is believed that you are familiar with its usage:

var trimedstring = ' Hello World '. Trim ();
We can also implement our own trim function:

if (! String.prototype.trim) {  String.prototype.trim = function () {    return this.replace (/^[\s\ufeff\xa0]+|[ \s\ufeff\xa0]+$/g, ');  };}
Perhaps people will be curious, the above a string of regular expression is what east, usually we use/^\s+|\s+$/g to match before and after the space, why also add the following a large string of characters? Because ES5 specifies that \s contain spaces and newline characters, and the spaces contain two Unicode characters U+feff and u+00a0, the following expression will return true if it is run under the console:

/^\s+$/.test ("\ufeff\u00a0")
So I suggest you add.


Date.now ();

This function returns a timestamp for the current time, and the result is the same as the new Date (). GetTime () and (+new date), you can try it.

Date.prototype.toISOString ();

The Toisostring function returns an ISO-formatted string representing the current time, in the form of Yyyy-mm-ddthh:mm:ss.sssz, representing a time uniform of 0 time zone standard Time, followed by the zero meaning of Z.


ES5 one of the new functions: Array, JSON, String, Date

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.