Elementary introduction to JavaScript Standard Object _ basic knowledge

Source: Internet
Author: User
Tags current time iso 8601 iso 8601 format local time tojson wrapper javascript array

In the JavaScript world, everything is an object.

However, some objects are not quite the same as other objects. To distinguish the type of an object, we use the typeof operator to get the type of the object, which 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 , function and undefined distinct from other types. The type of special attention null is the object Array type also object , if we use typeof will not be able to distinguish between null , Array and the usual sense of object-- {} .

Wrapping Objects

number, boolean and string all have wrapping objects. Yes, in JavaScript, strings also distinguish between string types and their wrapper types. Wrapping objects with new create:

var n = new number (123); 123, a new wrapper type was generated
var B = Boolean (TRUE);//True, the new wrapper type was generated
var s = A/b (' str ');//' str ', new wrapper type generated

Although the wrapper objects look exactly the same as the original values, they appear exactly the same, but their type has changed object ! Therefore, the wrapper object and the original value === are returned with the comparison false :

typeof new Number (123); ' Object '
new number (123) = = 123;//False
typeof new Boolean (TRUE);//'
new Boolean (true) = = T Rue False
typeof new String (' str ');//' object '
new string (' str ') = = = ' str ';//False

So the idle egg ache also do not use wrapping Object! Especially for string type!!!

Date

In JavaScript, an Date object is used to represent a date and time.

To get the system current time, use:

var now = new Date ();
Now Wed June 2015 19:49:22 gmt+0800 (CST)
now.getfullyear ();//2015, Year
Now.getmonth ();//5, Month, note Month range is 0~11,5 representation June
now.getdate ();//24, representing 24th
now.getday ();//3, indicating Wednesday
now.gethours ();//19, 24-hour system
now.getminutes () ; 49, Min
now.getseconds ();//22, SEC
now.getmilliseconds ();//875, milliseconds
now.gettime ();//1435146562875 to Time stamp represented by number form

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

If you want to create an object that specifies a date and time Date , you can use the following:

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

You might have noticed a very, very, very, very, very, very, very, very, very good place. The month range of JavaScript is expressed as a 0~11,0. January, 1 means February ..., so to say June, we passed in 5! This is definitely the JavaScript designer's brain pumping, but now it's impossible to fix it.

The second way to create a specified date and time is to parse a string that conforms to the ISO 8601 format:

var d = date.parse (' 2015-06-24t19:49:22.875+08:00 ');
D 1435146562875

But it returns not Date an object, but a timestamp. But with a timestamp you can easily convert it to a Date :

var d = new Date (1435146562875);
D Wed June 2015 19:49:22 gmt+0800 (CST)

Time

DateThe time the object represents is always displayed in the browser's time zone, but we can display both local time and adjusted UTC time:

var d = new Date (1435146562875);
D.tolocalestring (); ' 2015/6/24 7:49:22 ', local time (Beijing time zone +8:00), the displayed string is related to the format set by the operating system
d.toutcstring ();//' Wed, June 2015 11:49:22 GMT ', UTC time, 8 hour difference from local time

So how do you do time zone conversions in JavaScript? In fact, as long as we're passing a number type of timestamp, we don't have to worry about time zone conversions. Any browser can convert a timestamp correctly to local time.

So we just need to pass the timestamp, or read the timestamp from the database, and let JavaScript automatically convert to local time.

To get the current timestamp, you can use:

if (date.now) {
  alert (Date.now ());//older version IE has no now () method
} else {
  alert (new Date (). GetTime ());

Json

In JSON, there are just a few types of data:

Number: Exactly the same as the number of JavaScript;

Boolean: Is the JavaScript true or false;

string: is the JavaScript string;

null: is the JavaScript null;

array: Is the JavaScript array representation--[];

object: Is the JavaScript {...} The way it is represented.

And any combination of the above.

Serialization of

Let's first serialize the object of Xiaoming to a string in JSON format:

var xiaoming = {
  name: ' Xiaoming ',
  age:14,
  gender:true,
  height:1.65,
  grade:null,
  ' Middle-school ' : ' w3c\ ' Middle School ',
  skills: [' JavaScript ', ' Java ', ' Python ', ' Lisp ']
};

使用JSON.stringify()之后:

Json.stringify (xiaoming); ' {' name ': "Xiaoming", "Age": "Gender": true, "height": 1.65, "grade": null, "Middle-school": "\" w3c\ "Middle School", " Skills ": [JavaScript", "Java", "Python", "Lisp"]} '

To get some good output, you can add parameters and indent output:

Json.stringify (xiaoming, NULL, "");

Results:

{
 "name": "Xiaoming",
 "age": "
 Gender": true,
 "height": 1.65,
 "grade": null, "
 Middle-school": " \ "W3c\" Middle School, "
 skills": [  JavaScript,  Java,  Python,  Lisp
 ]
}

The second parameter controls how the key value of the object is filtered, and if we only want to output the specified property, we can pass in Array :

Json.stringify (xiaoming, [' Name ', ' skills '], ");

Results:

{
 "name": "Xiaoming",
 "skills": [  "JavaScript",  "Java",  "Python",  "Lisp"
 ]
}

You can also pass in a function so that each key pair of the object is 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 capitalizes all the attribute values:

{
 "name": "Xiaoming",
 "age": "
 Gender": true,
 "height": 1.65, "
 grade": null,
 " Middle-school ":" \ "w3c\" Middle School ",
 " skills ": [  JAVASCRIPT, JAVA,  PYTHON  ," LISP "
 ]
}

If we also want to control exactly how to serialize xiaoming, we can give you xiaoming a way to define a toJSON() method that directly returns the data that JSON should serialize:

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 ': ' xiaoming ', ' Age ': 14} '

Deserialization

To get a JSON-formatted string, we'll simply turn JSON.parse() it into a JavaScript object:

Json.parse (' [1,2,3,true] ');  [1, 2, 3, True]
json.parse (' {' name ': ' Xiaoming ', ' Age ':} ');//Object {name: ' Xiaoming ', age:14}
json.parse (' true '); True
json.parse (' 123.45 ');//123.45

JSON.parse()You can also receive a function to transform the parsed property:

Json.parse (' {' name ': ' Xiaoming ', ' Age ':} ', function (key, value) {
  //number * 2:
  if (key = = = ' name ') {return
    Valu E + ' classmate ';
  }
  return value;
}); Object {name: ' Xiao Ming classmate ', age:14}

The above article on the JavaScript standard object is small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.