JavaScript Learning record day9-Standard object

Source: Internet
Author: User
Tags gmt time zone iso 8601 iso 8601 format local time ming tojson wrapper yahoo weather api


JavaScript Learning record day9-Standard object


[TOC]



In the JavaScript world, everything is an object.



Some objects, however, are not the same as other objects. To distinguish the type of an object, we use thetypeofoperator 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,,,,numberstringbooleanfunctionandundefineddistinct from other types. The typenullof special attentionobjectisArrayAlso,objectif we use will betypeofindistinguishablenull, and inArraythe usual sense--object{}.


1. Packaging objects


In addition to these types, JavaScript also provides packaging objects, and the familiarity of Java's small partners must be clearintandIntegerthis ambiguous relationship.



number,booleanandstringboth have packaging objects. Yes, in JavaScript, a string also distinguishes betweenstringa type and its wrapper type. The wrapper object isnewcreated with:


var n = new Number (123); // 123, a new wrapper type is generated
var b = new Boolean (true); // true, a new wrapper type is generated
var s = new String (‘str’); // ‘str’, a new wrapper type is generated


Although the wrapper object looks exactly the same as the original value, the display is identical, but their type has changedobject! Therefore, the wrapper object and the original value===are returned with a comparisonfalse:


typeof new Number(123); // ‘object‘
new Number(123) === 123; // false

typeof new Boolean(true); // ‘object‘
new Boolean(true) === true; // false

typeof new String(‘str‘); // ‘object‘
new String(‘str‘) === ‘str‘; // false


<font color= "Red" > So don't use the wrapping object for the aching egg! Especially for string Types!!! </font>



What happens if weNumberBooleanStringdo not write when we use, and whennew?



At this point,,Number()Booleanand as aString()normal function, convert any type of data tonumber,booleanandstringtype (note not its wrapper type):


var n = Number (‘123’); // 123, equivalent to parseInt () or parseFloat ()
typeof n; // ‘number’

var b = Boolean (‘true’); // true
typeof b; // ‘boolean’

var b2 = Boolean (‘false’); // true! ‘false’ string conversion result is true! Because it is a non-empty string!
var b3 = Boolean (‘‘); // false

var s = String (123.45); // ‘123.45’
typeof s; // ‘string’


To summarize, there are a few rules to follow:


    • Do notnew Number()usenew Boolean(),new String()create packaging objects;
    • UseparseInt()orparseFloat()to convert any type tonumber;
    • TheString()method used to convert any type tostring, or directly invoke, an objecttoString();
    • It is not usually necessary to convert any type tobooleanre-judgment, because it can be written directlyif (myVar) {...};
    • typeofOperators can determine the,,,numberbooleanstringfunctionandundefined;
    • JudgeArrayto useArray.isArray(arr);
    • Judgingnullplease usemyVar === null;
    • Determine if a global variable existstypeof window.myVar === ‘undefined‘;
    • The function internally determines whether a variable existstypeof myVar === ‘undefined‘.


Finally have the careful classmate pointed out, any object has thetoString()method?nullandundefinedthere is no! This is true, except for these two special values, althoughnullthey are also disguised asobjecttypes.



The more careful classmate points out that thenumberobject calls thetoString()SyntaxError:


123.toString(); // SyntaxError


In this case, special treatment is needed:


123..toString (); // ‘123’, notice two points! The first point is interpreted as a decimal point
(123) .toString (); // ‘123’, [Recommended]
2. Date


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



To get the current time of the system, 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 range of the month is 0 ~ 11, 5 means June
now.getDate (); // 24, means 24
now.getDay (); // 3, means Wednesday
now.getHours (); // 19, 24-hour clock
now.getMinutes (); // 49, minutes
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 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 a Date object that specifies the dates and times, you can use:


var d = new Date(2015, 5, 19, 20, 15, 30, 123);d; // Fri Jun 19 2015 20:15:30 GMT+0800 (CST)


The month range of JavaScript is expressed in integers as 0~11, which represents0January, which1represents February ..., so to represent June, we passed in5!


JavaScript Date Object month value starting from 0, remember 0=1 month, 1=2 month, 2=3 month, ..., 11=12 month.


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 instead of a Date object, it returns a timestamp. But with a time stamp it is easy to convert it to a date:


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

TheDate.parse()string passed in using the actual month 01~12 is converted to a Date object after GetMonth () gets the month value of 0~11.


Time



The time represented by the Date object is always displayed in the browser's time zone, but we can display both the local time and the adjusted UTC time:


var d = new Date (1435146562875);
d.toLocaleString (); // ‘6/24/2015 7:49:22 PM’, local time (Beijing time zone 8:00), the displayed string is related to the format set by the operating system
d.toUTCString (); // ‘Wed, 24 Jun 2015 11:49:22 GMT’, UTC time, 8 hours difference from local time


So how do you do time zone conversions in JavaScript? In fact, as long as we pass a timestamp of anumbertype, we don't care about the time zone conversion. Any browser can convert a timestamp to the local time correctly.



What's a time stamp? The timestamp is an auto-increment integer that represents the moment that the GMT time zone starts at zero January 1, 1970, and the current number of milliseconds. Assuming that the time of the browser's computer is accurate, the time stamp numbers in the world, regardless of the time zone, are the same at the moment, so the timestamp can represent exactly one moment and is independent of the time zone.



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



To get the current timestamp, you can use:


‘Use strict’;

if (Date.now) {
     console.log (Date.now ()); // old version of IE does not have a now () method
} else {
     console.log (new Date (). getTime ());
}
3. Regular expressions


Strings are the most data structure involved in programming, and the need to manipulate strings is almost ubiquitous. For example, to determine whether a string is a legitimate email address, although it can be programmed to extract the substring before and after, and then judge whether it is a word and domain name, but this is not only cumbersome, and the code is difficult to reuse.



A regular expression is a powerful weapon used to match strings. Its design idea is to use a descriptive language to define a rule for a string, and any string that conforms to the rule, we think it "matches", otherwise the string is illegal.



So the way we judge whether a string is a legitimate email is:



Create a regular expression that matches the email;



Use the regular expression to match the user's input to determine whether it is legal.



Because the regular expression is also represented by a string, we first know how to describe the character with characters.



In regular expressions, if a character is given directly, it is exactly the exact match. To match a\dnumber,\wyou can match a letter or a number, so:



‘00\d‘Can match‘007‘, but cannot match‘00A‘;



‘\d\d\d‘can match‘010‘;



‘\w\w‘can match‘js‘;



.Can match any character, so:



‘js.‘Can match‘jsp‘,‘jss‘, and‘js!‘so on.
To match a variable-length character, in a regular expression, with a representation of*any character (including 0), with a representation of+at least one character, representing?0 or 1 characters, with a representation of{n}n characters, represented by{n,m}n-m characters:



Take a look at a complex example:\d{3}\s+\d{3,8}.



Let's read from left to right:



\d{3}Indicates a match of 3 digits, for example‘010‘;



\sCan match a space (also including tab and other white space characters), so that\s+there is at least one space, such as matching‘ ‘,‘\t\t‘etc.;



\d{3,8}Represents a 3-8 number, for example‘1234567‘.



Together, the above regular expression can match a telephone number with an area code separated by any space.



What if you want to match‘010-12345‘a number like this? Because '-' is a special character, it is escaped in the regular expression,‘\‘so the above is the regular\d{3}\-\d{3,8}.



However, there is still no match‘010 - 12345‘because there are spaces. So we need more complex ways of matching.



Advanced



To make a more accurate match, you can use a[]representation range, such as:



[0-9a-zA-Z\_]Can match a number, letter, or underscore;



[0-9a-zA-Z\_]+Can match a string of at least one number, letter, or underscore, for example, and‘a100‘‘0_Z‘‘js2015‘so on;



[a-zA-Z\_\$][0-9a-zA-Z\_\$]*It can be matched by a letter or underscore,$preceded by a string consisting of a number, letter, or underscore, which is$the variable name allowed by JavaScript;



[a-zA-Z\_\$][0-9a-zA-Z\_\$]{0, 19}More precisely limit the length of a variable to 1-20 characters (1 characters before + 19 characters later).



A|BCan matchAorB, so(J|j)ava(S|s)criptcan match‘JavaScript‘,‘Javascript‘,‘javaScript‘or‘javascript‘.



^Represents the beginning of a row,^\dindicating that a number must begin.



$Represents the end of a line, indicating that it\d\$must end with a number.



You may have noticed that JS can also match ' JSP ', but with ^js$ it becomes the whole line match, it can only match ' JS '.



Regexp



With the knowledge of readiness, we can use regular expressions in JavaScript.



JavaScript has two ways of creating a regular expression:



The first way is by/正则表达式/writing it directly, and the second way is bynew RegExp(‘正则表达式‘)creating a RegExp object.



The two formulations are the same:


var re1 = /ABC\-001/;var re2 = new RegExp(‘ABC\\-001‘);console.log(re1); // /ABC\-001/console.log(re2); // /ABC\-001/


Note that if you use the second notation because of the escape problem of the string, the two of the string\\is actually one\.



Let's look at how to tell if a regular expression matches:


var re = /^\d{3}\-\d{3,8}$/;console.log(re.test(‘010-12345‘)); // trueconsole.log(re.test(‘010-1234x‘)); // falseconsole.log(re.test(‘010 12345‘)); // false


The method of the RegExp objecttest()is used to test whether a given string conforms to a condition.



Slicing a string



Using regular expressions to slice a string is more flexible than a fixed character, see the normal segmentation code:


console.log(‘a b   c‘.split(‘ ‘)); // [‘a‘, ‘b‘, ‘‘, ‘‘, ‘c‘]


Well, you can't recognize contiguous spaces, try using regular expressions:


console.log(‘a b   c‘.split(/\s+/)); // [‘a‘, ‘b‘, ‘c‘]


No matter how many spaces can be divided normally. To join, try:


console.log(‘a,b, c  d‘.split(/[\s\,]+/)); // [‘a‘, ‘b‘, ‘c‘, ‘d‘]


Try again;:


console.log(‘a,b;; c  d‘.split(/[\s\,\;]+/)); // [‘a‘, ‘b‘, ‘c‘, ‘d‘]


If the user enters a set of tags, next time remember to use regular expressions to convert the nonstandard input into the correct array.



Group



In addition to simply judging whether a match is matched, the regular expression also has the power to extract substrings. The()Grouping (group) to be extracted is represented by the. Like what:



^(\d{3})-(\d{3,8})$Two groups are defined separately, and the area code and local numbers can be extracted directly from the matching string:


var re = /^(\d{3})-(\d{3,8})$/;re.exec(‘010-12345‘); // [‘010-12345‘, ‘010‘, ‘12345‘]re.exec(‘010 12345‘); // null


If a group is defined in a regular expression, the substring can be extracted from the RegExp object using aexec()method.



exec()After the match succeeds, the method returns oneArray, the first element is the entire string to which the regular expression matches, and the subsequent string represents the successful substring.



exec()Method is returned when a match failsnull.



Extracting substrings is useful. Look at a more vicious example:


var re = /^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$/;re.exec(‘19:05:30‘); // [‘19:05:30‘, ‘19‘, ‘05‘, ‘30‘]


This regular expression can directly identify the legal time. However, there are times when it is not possible to fully validate with regular expressions, such as identifying dates:



var re =/^ (0[1-9]|1[0-2]|[ 0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[ 0-9]) $/;
For the ' 2-30 ', ' 4-31 ' such illegal date, with regular or not recognized, or write out to be very difficult, then the need for a program to identify the cooperation.



Greedy match



In particular, a regular match is a greedy match by default, which is to match as many characters as possible. For example, match the following numbers0:


var re = /^(\d+)(0*)$/;re.exec(‘102300‘); // [‘102300‘, ‘102300‘, ‘‘]


Because\d+of the greedy match, directly the back of0all matching, the result0*can only match the empty string.



You must let \d+ use a non-greedy match (that is, as few matches as possible) in order to match the back of the 0, add a? You can let the \d+ use a non-greedy match:


var re = /^(\d+?)(0*)$/;re.exec(‘102300‘); // [‘102300‘, ‘1023‘, ‘00‘]


Global Search



JavaScript regular expressions also have several special flags, most commonly usedgto represent global matches:


var r1 = /test/g;// 等价于:var r2 = new RegExp(‘test‘, ‘g‘);


A global match can executeexec()the method multiple times to search for a matching string. When we specify agflag, each time it is runexec(), the regular expression itself updates thelastIndexproperty, representing the last index to which it was last matched:


var s = ‘JavaScript, VBScript, JScript and ECMAScript’;
var re = / [a-zA-Z] + Script / g;

// Use global matching:
re.exec (s); // [‘JavaScript’]
re.lastIndex; // 10

re.exec (s); // [‘VBScript’]
re.lastIndex; // 20

re.exec (s); // [‘JScript’]
re.lastIndex; // 29

re.exec (s); // [‘ECMAScript’]
re.lastIndex; // 44

re.exec (s); // null, no match until the end


The global match is similar to a search and therefore cannot be used, so it/^...$/will only match at most once.



The regular expression can also specifyiflags, which indicate that the case is ignored, and the flag indicates that ammultiline match is performed.



Practice



Please try to write a regular expression that validates the email address. Version one should be able to verify a similar email:


‘Use strict’;

var re = /^[az]([a-z0-9]*[-._]?[a-z0-9]+)*@([a-z0-9]*[-_]?[a -z0-9] +) + [\.] [az] {2,3} ([\.] [az] {2})? $ / i;

// test:
var
     i,
     success = true,
     should_pass = [‘[email protected]’, ‘[email protected]’, ‘[email protected]’, ‘[email protected]’],
     should_fail = [‘test # gmail.com’, ‘[email protected]’, ‘bill% [email protected]’, ‘@ voyager.org’];
for (i = 0; i <should_pass.length; i ++) {
     if (! re.test (should_pass [i])) {
         console.log (‘Test failed:‘ + should_pass [i]);
         success = false;
         break;
     }
}
for (i = 0; i <should_fail.length; i ++) {
     if (re.test (should_fail [i])) {
         console.log (‘Test failed:‘ + should_fail [i]);
         success = false;
         break;
     }
}
if (success) {
     console.log ('Test passed!');
}


Version two can verify and extract the name of the email address:


‘Use strict’;

var re = /^\<([a-zA-Z\_\.\s]+)\>\s+([a-zA-Z0-9\_\.]+\@[a-zA-Z0 -9 \ _] + \. [A-zA-Z] +) $ /;

// test:
var r = re.exec (‘<Tom Paris> [email protected]‘);
console.log (r);
if (r === null || r.toString ()! == [‘<Tom Paris> [email protected]’, ‘Tom Paris’, ‘[email protected]’]. toString ()) {
     console.log ('Test failed!');
}
else {
     console.log ('Test succeeded!');
}
4. JSON


JSON is the abbreviation for JavaScript Object notation, which is a data interchange format.



Before JSON appeared, everyone used XML to pass the data. Because XML is a plain text format, it is suitable for exchanging data on the network. XML itself is not complicated, but, with a lot of complex specifications such as DTDs, XSD, XPath, XSLT, and so on, any normal software developer will feel a big head when it comes to XML, and finally we find that even if you work hard for a few months, you may not be able to understand the specification of XML.



Finally, on a day in 2002, Grass Crockford Douglas Crockford, a software engineer who had been fooled by a handful of giant software companies in order to save a deep abyss, invented the ultra-lightweight data Interchange format of JSON.



As a senior architect of Yahoo, Douglas has a natural fondness for JavaScript. The JSON he designed is actually a subset of JavaScript. In JSON, there are a total of several data types:



Number: Exactly the same as JavaScriptnumber;
Boolean: is JavaScripttrueorfalse;
String: It's JavaScriptstring;
Null: it is JavaScriptnull;
Array: That's theArrayway JavaScript is represented--[];
Object: Is the way JavaScript is{ ... }represented.
And any combination of the above.



And, JSON is dead. The character set must be UTF-8, which means that there is no problem with multiple languages. For unified parsing, the JSON string must be in double quotes"", and the key of object must also be double-quoted"".



Because JSON is very simple, it quickly swept the web world and became the ECMA standard. Almost all programming languages have libraries that parse JSON, and in JavaScript we can use JSON directly, because JavaScript has built-in JSON parsing.



To turn any JavaScript object into JSON is to serialize the object into a JSON-formatted string so that it can be passed to other computers over the network.



If we receive a string in JSON format, we just need to deserialize it into a JavaScript object, and we can use it directly in JavaScript.



Serialization of
Let's first serialize this object into a JSON-formatted string:


‘use strict‘;

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

var s = JSON.stringify(xiaoming);
console.log(s);


To output a good look, you can add parameters to the output by indentation:



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



Results:


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


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



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



Results:


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


You can also pass in a function so that each key-value pair of an object is processed first by the function:


function convert(key, value) {
    if (typeof value === ‘string‘) {
        return value.toUpperCase();
    }
    return value;
}


JSON.stringify(xiaoming, convert, ‘ ‘);



The above code capitalizes all attribute values:


{
     "name": "Xiao Ming",
     "age": 14,
     "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, you can define a Tojson () method for Xiaoming to return directly the data that the JSON should serialize:


var xiaoming = {
     name: ‘Xiao Ming’,
     age: 14,
     gender: true,
     height: 1.65,
     grade: null,
     ‘Middle-school’: ‘\" W3C \ "Middle School’,
     skills: [‘JavaScript’, ‘Java’, ‘Python’, ‘Lisp’],
     toJSON: function () {
         return {// only output name and age, and changed the key:
             ‘Name’: this.name,
             ‘Age’: this.age
         };
     }
};

var r = JSON.stringify (xiaoming); // {"Name": "小 明", "Age": 14}
console.log (r);


To get a string in JSON format, we use Json.parse () to turn 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’); // true
JSON.parse (‘123.45‘); // 123.45


JSON.parse()You can also receive a function that transforms the parsed property:


‘Use strict’;

var obj = JSON.parse (‘{" name ":" Xiaoming"," age ": 14}‘, function (key, value) {
     if (key === ‘name’) {
         return value + ‘classmate’;
     }
     return value;
});
console.log (JSON.stringify (obj)); // {name: ‘Xiao Ming classmate’, age: 14}


Practice



Use the browser to access the Yahoo Weather API, view the returned JSON data, and then return to the city, temperature forecasts, and other information:


‘Use strict’

var url = ‘https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json’;
// Get JSON from a remote address:
$ .getJSON (url, function (data) {
     // Get results:
     var city = data.query.results.channel.location.city;
     var forecast = data.query.results.channel.item.forecast;
     var result = {
         city: city,
         forecast: forecast
     };
     alert (JSON.stringify (result, null, ‘‘));

}); 


Learning Reference Tutorial: http://www.liaoxuefeng.com



JavaScript Learning record day9-Standard object


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.