Talking about JavaScript standard objects and javascript objects

Source: Internet
Author: User
Tags iso 8601 iso 8601 format tojson

Talking about JavaScript standard objects and javascript objects

In the JavaScript world, everything is an object.

However, some objects are not the same as other objects. To differentiate object types, we usetypeofOperator to get the object type. It always returns a string:

typeof 123; // 'number'typeof NaN; // 'number'typeof 'str'; // 'string'typeof true; // 'boolean'typeof undefined; // 'undefined'typeof Math.abs; // 'function'typeof null; // 'object'typeof []; // 'object'typeof {}; // 'object'

Visible,number,string,boolean,functionAndundefinedDifferent from other types. Special notenullIsobject,ArrayThe type is alsoobjectIf we usetypeofCannot be distinguishednull,ArrayAnd the object in the general sense --{}.

Packaging object

number,booleanAndstringThere are packaging objects. Yes, strings are also differentiated in JavaScript.stringType and its packaging type. For packaging objectsnewCreate:

Var n = new Number (123); // 123, A new packaging type var B = new Boolean (true) is generated; // true, A new packaging type var s = new String ('str'); // 'str' is generated, and a new packaging type is generated.

Although the packaging object looks exactly the same as the original value, it is displayed exactly the same, but their type has changedobjectNow! Therefore, use===Comparison returnsfalse:

typeof new Number(123); // 'object'new Number(123) === 123; // falsetypeof new Boolean(true); // 'object'new Boolean(true) === true; // falsetypeof new String('str'); // 'object'new String('str') === 'str'; // false

Therefore, do not use packaging objects for idle egresses! Especially for the string type !!!

Date

In JavaScript,DateObjects are used to represent dates and times.

To obtain the current system time, use:

Var now = new Date (); now; // Wed Jun 24 2015 19:49:22 GMT + 0800 (CST) now. getFullYear (); // 2015, year now. getMonth (); // 5, month. Note that the month range is 0 ~ Indicates June now. getDate (); // 24, indicating the 24 now. getDay (); // 3, indicating Wednesday now. getHours (); // 19, now in 24-hour format. getMinutes (); // 49, minute now. getSeconds (); // 22, seconds now. getMilliseconds (); // 875, milliseconds now. getTime (); // 1435146562875, timestamp in the form of number

Note that the current time is the time the browser obtains from the local operating system, so it is not necessarily accurate, because you can set the current time to any value.

If you want to createDateObject, you can use:

var d = new Date(2015, 5, 19, 20, 15, 30, 123);

You may have observed that the JavaScript month range is expressed as an integer between 0 and 0 ~ , 0 indicates January 1, 1 indicates January 1 ......, Therefore, we want to input 5 for June 1, June! This is definitely because the JavaScript designer had a brain attack at the time, but it is impossible to fix it now.

The second method to create a specified date and time is to parse a string in ISO 8601 format:

var d = Date.parse('2015-06-24T19:49:22.875+08:00');d; // 1435146562875

But it does not returnDateObject, but a timestamp. However, with a timestamp, you can easily convert it intoDate:

var d = new Date(1435146562875);d; // Wed Jun 24 2015 19:49:22 GMT+0800 (CST)

Time Zone

DateThe time indicated by the object is always displayed according to the time zone of the browser, but we can display both the local time and the adjusted UTC time:

Var d = new Date (1435146562875); d. toLocaleString (); // '2014/1/24 7:49:22 ', local time (Beijing Time Zone +). The displayed string is related to the format set by the operating system. toUTCString (); // 'wed, 24 Jun 2015 11:49:22 gmt', UTC time, 8 hours different from local time

So how to convert the time zone in JavaScript? In fact, as long as we passnumberThe timestamp type, so we don't have to worry about time zone conversion. Any browser can correctly convert a timestamp to a local time.

Therefore, we only need to pass the timestamp, or read the timestamp from the database, so that JavaScript can be automatically converted to the local time.

To obtain the current timestamp, you can use:

If (Date. now) {alert (Date. now (); // earlier IE versions do not have the now () method} else {alert (new Date (). getTime ());}

JSON

In JSON, there are several data types:

• Number: it is exactly the same as the JavaScript number;

• Boolean: true or false of JavaScript;

• String: string of JavaScript;

• Null: The JavaScript null;

• Array: the Array representation of JavaScript -- [];

• Object: The {...} representation of JavaScript.

And any combination above.

Serialization

Let's serialize Xiaoming to a JSON string:

Var xiaoming = {name: 'xiaoming ', age: 14, gender: true, height: 1.65, grade: null, 'middle-school ': '\ "W3C \" Middle School', skills: ['javascript ', 'java', 'python', 'lisp']};

After JSON. stringify () is used:

JSON. stringify (xiaoming); // '{"name": "James", "age": 14, "gender": true, "height": 1.65, "grade ": null, "middle-school": "\" W3C \ "Middle School", "skills": ["JavaScript", "Java", "Python ", "Lisp"]}'

To make the output look better, you can add a parameter and output it according to indentation:

JSON.stringify(xiaoming, null, ' ');

Result:

{"Name": "James", "age": 14, "gender": true, "height": 1.65, "grade": null, "middle-school ": "\" W3C \ "Middle School", "skills": ["JavaScript", "Java", "Python", "Lisp"]}

The second parameter is used to control how to filter the key value of an object. If we only want to output the specified attributeArray:

JSON.stringify(xiaoming, ['name', 'skills'], ' ');

Result:

{"Name": "James", "skills": ["JavaScript", "Java", "Python", "Lisp"]}

You can also input a function, so that each key-value pair of the object will be processed by the function first:

function convert(key, value) {  if (typeof value === 'string') {    return value.toUpperCase();  }  return value;}JSON.stringify(xiaoming, convert, ' ');

The code above converts all attribute values into uppercase values:

{"Name": "James", "age": 14, "gender": true, "height": 1.65, "grade": null, "middle-school ": "\" W3C \ "middle school", "skills": ["JAVASCRIPT", "JAVA", "PYTHON", "LISP"]}

If we want to precisely control how to serialize JamesxiaomingDefinetoJSON()Directly return the data to be serialized in JSON:

Var xiaoming = {name: 'xiaoming ', age: 14, gender: true, height: 1.65, grade: null, 'middle-school ': '\ "W3C \" Middle School', skills: ['javascript ', 'java', 'python', 'lisp'], toJSON: function () {return {// only name and age are output, and key: 'name': this. name, 'age': this. age };}; JSON. stringify (xiaoming); // '{"Name": "James", "Age": 14 }'

Deserialization

To obtain a JSON string, we useJSON.parse()Convert it into a JavaScript Object:

JSON. parse ('[1, 2, 3, true]'); // [1, 2, 3, true] JSON. parse ('{"name": "Xiao Ming", "age": 14}'); // Object {name: 'xiao Ming ', age: 14} JSON. parse ('true'); // trueJSON. parse ('2017. 45'); // 123.45

JSON.parse()You can also receive a function to convert the parsed attributes:

JSON. parse ('{"name": "James", "age": 14}', function (key, value) {// set number * 2: if (key = 'name') {return value + 'classmate ';} return value;}); // Object {name: 'James class', age: 14}

The above discussion about the JavaScript standard object is all the content shared by the small Editor. I hope you can give us a reference and support the house of helping customers.

Related Article

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.