Directory:

  1. Comparison operator
  2. Multiline string, template string
  3. Strict mode
  4. Function definitions and calls
  5. Variable scope and destruct assignment, NameSpace, block-level scope let, const
  6. methods
  7. Higher-order functions map, Reduce, and Filter
  8. closure

Let’s take it one at a time:

Comparison operators:

  • == equal = true = true = true = true

  • === absolute equal, type is the same, value is the same, judge true

  • ! = = is not equal to

  • This is a flaw in JS, try not to use == comparisons

    Floating-point problem: console.log((1/3)===(1-2/3)) results in false, although values are all equal to 1/3 try to avoid using decimal calculations because of accuracy issues

Template string in ES6:

Any character inserted into a new line is part of the template string. Using a normal string, you can get a multi-line string in the following ways:

console.log('string text line 1\n' +
'string text line 2');
Copy the code

“string text line 1 string text line 2”

To get a multi-line string with the same effect, just use the following code:

console.log(`string text line 1
string text line 2`);
Copy the code

“string text line 1 string text line 2”

Insert expression:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    <script>
        
        var a=10;
        var b = 20;
        console.log(`a = ${a},b = ${b}`);

    </script>
</body>
</html>
Copy the code

As you can see from the code above, you need to put the expression ${} into ‘ ‘to execute correctly.

MDN

Strict mode:

Strict mode makes some changes to the normal JavaScript semantics.

  1. Strict mode eliminates some of the original silent errors (undefined) by throwing errors.
  2. Strict mode fixes some flaws that make it difficult for JavaScript engines to perform optimizations: sometimes, the same code can run faster in strict mode than in non-strict mode.
  3. Strict mode disables some syntax that might be defined in future versions of ECMAScript.
'use strict';
function getAge(){
    var y = new Date().getFullYear();
    return y - this.birth;
}
var xiaoming = {
    name:'Ming'.birth:2000.age:getAge
}; 
// If the use strick function is enabled, the result will be different
var fn = xiaoming.age;
console.log(fn()); 
Copy the code

Specific link: MDN

Function definitions and calls:

To define a function:

Definition Method 1

Absolute value function

function abs(x){
    return x;
}else{
    return -x;
}
Copy the code

Once the return function is finished, the result is returned

Definition method 2

var abs = function(x){
    return x;
}else{
    return -x;
}
Copy the code

Function (x){} = function(x){} = function(x){}

Call function:

abs(10)
abs(-10)
Copy the code

** Parameter problem: javascript can pass any parameter or no parameter. How do I throw an exception, assuming there are no arguments?

var abs = function(x){
    // Throw an exception manually
    if (typeofx ! = ='number') {
        throw 'not a number';
    }
    if (x>=o) {
        return x;
    }else{
        return-x; }}Copy the code

The arguments object:

The argument object is an array of arguments passed to the function. The argument object is an array of arguments passed to the function. 1. The arguments object is inseparable from the Function. The arguments object cannot be created explicitly. The arguments object is only available at the start of the function. How to use arguments: Although the Arguments object is not an array, individual arguments are accessed in the same way as the elements of an array. For example,arguments[0],arguments[1],… The arguments [n]. You can access the parameters in js without specifying their names. For example:

function test() {
        var s = ' ';
        for (var i = 0; i < arguments.length; i++) {
            alert(arguments[i]);
            s += arguments[i] + ', ';
        }
        return s;
}
test("name"."age");
Copy the code

The results for the name, age

Rest parameters

For example: a function defines two arguments, but a third argument is passed in. How do I get the third argument?

function test(a,b){
    console.log('a->'+a);
    console.log('b->'+b);
    // The previous method takes the third element:
    if (arguments.length>2) {
        for(var i = 2; i<arguments.length; i++){console.log(arguments[i])
        }
    }
}
// Present method (REST parameters) : define rest parameters in the function
function test1(a,b,... rest){
    console.log('a->'+a);
    console.log('b->'+b);
    console.log(rest);
}
Copy the code

The scope of a variable:

The scope of a variable:

function a(){
    var x = 1;
    Internal functions can access members of external functions, and vice versa
    function aa(){
        var y = x +1; / / 2
    }
    // External access to the internal function variables, will not work
    var z = y+1; / / an error
}
Copy the code
function foo(a,b){
    var x = 1;
    function bar(){
        var x = 'A';
        console.log(x);
    }
    console.log(x);
    bar();
}
foo();
Copy the code

1 A

Global object Window

'use strict';
window.alert('call Windows. Alert');
var old_alert = window.alert;
window.alert = function(){
    alert('Cannot use the alert method');
}
window.alert = old_alert;
alert('Now I can use the alert method again.');
Copy the code

Call result: only execute twice, the first output –> call windows.alert; The second output –> can use the alert method again

Let keyword:

Local scope let ES6let keyword to solve the problem of local scope conflict, now recommend everyone to use let to define local variables

function aaa() {
for(vari=0; i<100; i++){console.log(i)
}
console.log(i+1); / / the problem? I can be used outside of this scope
}

// After using let
function aaa() {
for(leti=0; i<100; i++){console.log(i)
}
console.log(i+1); //Uncaught ReferenceError: i is not defined
}
Copy the code

Const keyword:

After ES6, we define constants as const;

const PI = '3.14';
console.log(PI);
PI = '123'; // An error is reported indicating that constants cannot be modified
Copy the code

NameSpace:

Prevent the occurrence of duplicate name and named pollution;

var MYAPP = {};
var MYAPP2 = {};
MYAPP.name = 'myapp';
MYAPP.version = '1.0';
MYAPP.foo = function(){
    console.log("Test");
};
MYAPP.foo();
MYAPP2.name = 'myapp';
MYAPP2.version = '1.0';
MYAPP2.foo = function(){
    console.log("The test 2");
};
MYAPP2.foo();
Copy the code

Methods:

A method is a function placed inside an object. An object has only two things: properties and methods

var xiaoming = {
    name:'Ming'.birth:2000.age:function(){
        var y = new Date().getFullYear();
        return y -this.birth; }};console.log(xiaoming.age());
Copy the code

Member attributes are only responsible for child methods, not grandchild methods.

var xiaoming  = {
    name:'Ming'.birth:2000.age:function (){
        // Save the xiaoming object
        var that = this;
        function getAgeFromBirth(){
            var y  =  new Date().getFullYear();
            // If you do not save, the birth attribute is not found here
            return y - that.birth;
        }
        returngetAgeFromBirth(); }}console.log(xiaoming.age());
Copy the code

To solve this problem, we introduce the apply keyword;

The apply method controls what this refers to, and it takes two arguments. The first is getArg, which object to use, and the second is an array;

// Fix the js bug
function getAge(){
    var y = new Date().getFullYear();
    return y - this.birth;
}
var xiaoming = {
    name:'Ming'.birth:2000.age :getAge
};
//apply(x,y);
// The first argument is the required reference to this in getAge (not null).
// The second argument is an array by default, indicating the type of the argument passed in
console.log(getAge.apply(xiaoming,[]));
Copy the code

Higher-order functions use:

== Map, Reduce, and filter==

Map: Square each number

function pow(x){
    return x * x;
}
var arr = [1.2.3.4.5.6.7.8.9];
var result = arr.map(pow);
console.log('='+result);
Copy the code

Reduce: implements accumulation

var arr = [1.2.3.4.5];
//1+2-->3 x
//x+4-->7 x
//x+5-->12 x
var result = arr.reduce(function(x,y){
    return x+y;
});
console.log(result);
Copy the code

Filter: Filters out the values that do not meet the requirements of the function

var arr = [1.2.3.4.5.6.7];
var r = arr.filter(function(x){
    return x%2! = =0;
});
console.log(r);
Copy the code

Closure:

Closure introduction:

// Global variables can be accessed from within a function
var n = 999;
function f1(){
    console.log(n);
} 

// The variables inside the function cannot be accessed externally
function f1(){
    var n = 999;
}
console.log(n); 
Copy the code

Using closures to implement external references to internal information:

function f1(){
    var n = 999;
    function f2(){
        console.log(n);
    }
    return f2;
}
var res = f1();
res();
Copy the code

Implementation of complex closures:

// Close complex code segments
function createIncermentor(start){
    return function(){
        return start++;
    };
}
var inc = createIncermentor(10);
console.log(inc());
console.log(inc());
console.log(inc());
Copy the code

Results: 10, 11, 12

Define the class:

function Person(){
    var _age;
    function setAge(n){
        _age = n;
    }
    function getAge(){
        return _age;
    }
    //var obj = {} is an object
    return {
        name:name,
        getAge:getAge,
        setAge:setAge
    };
}
var p1 = Person("xbhog");
p1.setAge(88);
console.log(p1.getAge());
Copy the code

Results: 88

From:

JavaScript | MDN

God said JavaScript