JavaScript learning notes

Posted by ibbo on Fri, 18 Feb 2022 14:11:56 +0100

3, Standard object

1. Use the typeof operator to obtain the type of object. Note that the type of NaN is number, and the types of null, array and object {} are object:

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'

2. "Number, boolean and string all have wrapper objects", which is similar to the operation in java, such as new Number(12). In this way, a number wrapper object is created, which is not equal to 12. However, if new is omitted, Number(), Boolean(), and string () are normal functions, but this is not recommended. Pay attention to the rules that must be observed in the tutorial summary, in which "use String() to convert any type to string, or directly call the toString() method of an object", "an object" does not include null and undefined (there is no toString method).

Note that "the number object calls toString() to report SyntaxError". In fact, 123 in the following code will be implicitly wrapped as a number object. In addition, 123 ". of toString() It is not clear whether it is a decimal point symbol or through "." To call the method because there is no 123 ToString is a floating-point number, so an error will be reported; And 123 In toString() (equivalent to 123.0.toString()), the first point is interpreted as the decimal point of floating point number, and the second point is interpreted as object access, so there is no error:

123.toString(); // SyntaxError

// Special treatment
123..toString(); // '123', notice two points!
(123).toString(); // '123', it is recommended to use this method, and the parser will not be confused when parsing

These grammars are really Tiankeng, suffocating...

3. Create a Data object with specified Date and time in two ways: (1) pass in the values of year, month, day, hour, minute, second and millisecond. Note that "the month value of Date object in JavaScript starts from 0, 0 = January, 1 = February, 2 = March,..., 11 = December":

var d = new Date(2021, 7, 14, 15, 16, 20, 235);
d; // Tue Aug 14 2021 15:16:20 GMT+0800 (China standard time)

(2) Parse a string conforming to ISO 8601 format, return a timestamp, and then convert it into a Date object, but "when using Date.parse(), the string passed in uses the actual month 0112, and the month value obtained by getMonth() after converting it into a Date object is 011". The month of the printed Date object is the actual month, +8: 00 is to express that Beijing time is 8 hours earlier than UTC (world standard time):

var time_stamp = Date.parse('2015-06-24T19:49:22.875+08:00');
time_stamp; // 1435146562875, this is a timestamp

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

When creating the Date object in the first way and obtaining the month through the getMonth method, the month is 0 ~ 11, corresponding to 1 ~ 12.

4. "The design idea of Regular Expression is to define a rule for strings in a descriptive language. Strings that meet the rules are matched, otherwise they are 'illegal'.".

5. In regular expressions, \ d can match a number, \ w can match a letter or number, \ s can match a white space character (a character such as a space or Tab) Can match any character; If matching variable length characters, "use * to represent any character (including 0), use + to represent at least one character, use? To represent 0 or 1 characters, use {n} to represent n characters, and use {n,m} to represent n-m characters". In addition, special characters (characters other than numbers and letters) need to be escaped with \ in regular expressions, such as -$ And so on. In the string, \ also needs to be escaped into the form of \. Note that there are two ways to learn js to form regular expressions: "the first way is to write them directly through / regular expression / and the second way is to create a RegExp object through new RegExp('regular expression '):

var re1 = /ABC\-001/;
var re2 = new RegExp('ABC\\-001');

re1; // /ABC\-001/
re2; // /ABC\-001/

"The test() method of RegExp object is used to test whether the given string meets the conditions"

var re = /^\d{3}\-\d{3,8}$/;
re.test('010-12345'); // true
re.test('010-1234x'); // false
re.test('010 12345'); // false

6. If a group is defined in the regular expression (the group to be extracted is represented by brackets ()), you can extract the substring on the RegExp object with the exec method and return an array. The first element is the whole string matched by the regular expression, and the rest is the substring:

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

In the following example, if the parameter 'ex30', '2' in the regular expression is illegal, it will only determine whether the date returned by the method 'exre' is the legal date.

var re = /^(0[1-9]|1[0-2]|[0-9])-(0[1-9]|1[0-9]|2[0-9]|3[0-1]|[0-9])$/;

7. "Regular matching is greedy matching by default, that is, matching as many characters as possible". The following \ d + matches at least one number, and (0 *) does not match characters because it is greedy matching. Add "0 *" after \ d +? (0 or 1 characters) is a non greedy match:

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

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

8. Global search "you can execute the exec method multiple times to search for a matching string. After specifying the g flag, each time you run exec(), the regular expression itself will update the lastIndex attribute, indicating the last index matched last time":

var r1 = /test/g;
// Equivalent to:
var r2 = new RegExp('test', 'g');

Note that "global matching is similar to search, so you can't use / ^... $/, which will only match once at most; regular expressions can also specify i flag to ignore case, and m flag to perform multi line matching".

9. Practice writing regular expressions that verify Email addresses like:

'use strict';
var re = /^[0-9a-z\.]+\@[0-9a-z]+\.[a-z]{3}$/;
// Test:
var
    i,
    success = true,
    should_pass = ['someone@gmail.com', 'bill.gates@microsoft.com', 'tom@voyager.org', 'bob2015@163.com'],
    should_fail = ['test#gmail.com', 'bill@microsoft', 'bill%gates@ms.com', '@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!');
}

Practice writing regular expressions that verify and extract Email addresses with names:

'use strict';
var re = /^\<([a-zA-Z\s]+)\>\s+([a-z]+\@[a-z]+\.[a-z]{3})$/;
// Test:
var r = re.exec('<Tom Paris> tom@voyager.org');
if (r === null || r.toString() !== ['<Tom Paris> tom@voyager.org', 'Tom Paris', 'tom@voyager.org'].toString()) {
    console.log('Test failed!');
}
else {
    console.log('Test successful!');
}

10. "JavaScript has built-in JSON parsing. To turn any JavaScript object into JSON is to serialize the object into a string in JSON format", and the string in JSON must be enclosed in double quotation marks ".".

11. Serialization:

'use strict';

var xiaoming = {
    name: 'Xiao Ming',
    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);

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

// Output by indenting. If there are several spaces in the third parameter, it will be indented according to the number of spaces:
var s = JSON.stringify(xiaoming, null, '  ');
console.log(s);

result:
{
  "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 is the attribute array of the object to be output or a function that preprocesses each key value pair of the object
var s=JSON.stringify(xiaoming, ['name', 'skills'], '  ');
console.log(s);

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

"You can also define a toJSON() method for xiaoming to directly return the data that JSON should serialize". Example code:

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 name and age are output, and the key is changed:
            'Name': this.name,
            'Age': this.age
        };
    }
};

JSON.stringify(xiaoming); // '{"Name": "Xiao Ming", "Age":14}'

12. For a string in JSON format, execute the code JSON Parse() can 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() can also receive a function to convert the parsed attributes":

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

In the routine review, you can see the methods that cannot use the arrow function to define objects, Guide link After a look, The boss said that in the following code, "this in the arrow function does not point to the object a, and object a cannot form a scope (combined with the context, it is speculated that only in the function or globally can a scope be calculated) Therefore, if you go up to the global scope, this points to the global scope. If we use the definition method of ordinary function, the output will meet the expectation, because the scope of a.bar() function is bound to "a object" when it is executed

let a = {
  foo: 1,
  bar: () => console.log(this.foo)
}

a.bar()  //undefined

let a = {
  foo: 1,
  bar: function() { console.log(this.foo) }
}

a.bar()  // 1

The boss summarized three points:

  1. Arrow functions are suitable for pure function scenarios without complex logic or side effects. For example, they are used in the definition of callback functions of map, reduce and filter (especially when this is required for arrow functions as far as possible);
  2. Do not define the arrow function at the outermost layer, because it is easy to pollute the global scope by operating this inside the function. At least an ordinary function is wrapped outside the arrow function to control this within the visible range;
  3. The most attractive place is the beginning of the function, as described by the arrow. In the case of multi-layer function nesting, the simplicity of arrow function is not greatly improved, but affects the recognition of the scope of function. In this case, it is not recommended to use arrow function.

13.ps:get one Free weather api

Topics: Javascript Front-end