Home  >  Article  >  Web Front-end  >  Detailed introduction to JavaScript to improve learning ES6

Detailed introduction to JavaScript to improve learning ES6

WBOY
WBOYforward
2022-02-07 17:38:411716browse

This article brings you relevant knowledge about es6, including strict mode, higher-order functions, closures, recursion and other related issues. I hope it will be helpful to everyone.

Detailed introduction to JavaScript to improve learning ES6

Directory Overview

Detailed introduction to JavaScript to improve learning ES6

1. Strict Mode

  • JavaScript In addition to providing normal mode In addition, it also provides strict mode
  • ES5’s strict mode is a way to adopt restrictive JavaScript variants, that is, to run JS code under strict conditions
  • Strict mode will only be supported in IE10 or above browsers, and older browsers will be ignored
  • Strict mode makes some changes to normal JavaScript semantics:
    • Eliminates Javascript syntax Some unreasonable and imprecise aspects have been reduced, and some weird behaviors have been reduced.
    • Eliminate some unsafe aspects of code running and ensure the safety of code running.
    • Improve compiler efficiency and increase running speed.
    • Disable some syntax that may be defined in future versions of ECMAScript to pave the way for new versions of Javascript in the future. For example, some reserved words such as: class, enum, export, extends, import, super cannot be used as variable names
##1.1. Turn on strict mode

    Strict mode can be applied to
  • the entire script or to individual functions .
  • Therefore, when using it, we can divide the strict mode into two situations:
  • Turning on strict mode for scripts and Turning on strict mode for functions
1.1.2. Enable strict mode for the script

  • To enable strict mode for the entire script file, you need to

    put a specific statement before all statements

  • "use strict" or 'use strict'

    ##
    <script>
        &#39;user strict&#39;;
    	console.log("这是严格模式。");</script>
  • because
"use strict "

is enclosed in quotation marks, so older browsers will ignore it as an ordinary string. Some scripts are basically in strict mode, and some scripts are in normal mode. This is not conducive to file merging, so the entire script file can be placed in an anonymous function that is executed immediately. This creates a scope independently without affecting other script files.

<script>
	(function (){
    	&#39;use strict&#39;;
    	 var num = 10;
    	 function fn() {}
	})();   </script>

1.1.2. Enable strict mode for a function

If you want to enable strict mode for a function, you need to change
    "use strict"
  • or 'use strict'The statement is placed before all statements in the function body
        <!-- 为整个脚本(script标签)开启严格模式 -->
        <script>
            &#39;use strict&#39;;
            //   下面的js 代码就会按照严格模式执行代码
        </script>
        <script>
            (function() {
                &#39;use strict&#39;;
            })();
        </script>
        <!-- 为某个函数开启严格模式 -->
        <script>
            // 此时只是给fn函数开启严格模式
            function fn() {
                &#39;use strict&#39;;
                // 下面的代码按照严格模式执行
            }
    
            function fun() {
                // 里面的还是按照普通模式执行
            }
        </script>
Put
    "use strict"
  • on the first line of the function body, then The entire function runs in "strict mode".
  • 2. Changes in strict mode

Strict mode has made some changes to the syntax and behavior of JavaScript
  • 2.1. Variable regulations

In normal mode, if a variable is assigned a value without being declared, the default is a global variable
  • Strict mode prohibits this usage, and variables must be declared with the var command first. Then use
  • It is strictly prohibited to delete declared variables. For example, ``delete x` syntax is wrong
  •     <script>
            &#39;use strict&#39;;
            // 1. 我们的变量名必须先声明再使用
            // num = 10;
            // console.log(num);
            var num = 10;
            console.log(num);
            // 2.我们不能随意删除已经声明好的变量
            // delete num;
        </script>
  • 2.2. This points to the problem in strict mode

Previously
    this
  1. in the global scope function pointed to the window object
  2. this
  3. in the global scope function in strict mode It is undefined It can also be called without adding
  4. new
  5. when constructing the function before. When it is a normal function, this points to the global objectIn strict mode, if the constructor is called without
  6. new
  7. , this points to undefined, and if you assign a value to it, an error will be reported
  8. new
  9. The instantiated constructor points to the created object instance Timer
  10. this
  11. Still points to the window event or object Still pointing to the caller
  12.     <script>
            &#39;use strict&#39;;
    		//3. 严格模式下全局作用域中函数中的 this 是 undefined。
            function fn() {
                console.log(this); // undefined。
    
            }
            fn();
            //4. 严格模式下,如果 构造函数不加new调用, this 指向的是undefined 如果给他赋值则 会报错.
            function Star() {
                this.sex = &#39;男&#39;;
            }
            // Star();
            var ldh = new Star();
            console.log(ldh.sex);
            //5. 定时器 this 还是指向 window 
            setTimeout(function() {
                console.log(this);
    
            }, 2000);
            
        </script>
  13. 2.3. Function changes

Functions cannot have duplicate names
    Parameters
  1. The function must be declared in At the top level, new versions of JavaScript will introduce "block-level scoping" (introduced in ES6). In order to be in line with the new version,
  2. is not allowed to declare functions in non-function code blocks
  3.     <script>
            &#39;use strict&#39;;
            // 6. 严格模式下函数里面的参数不允许有重名
            function fn(a, a) {
               console.log(a + a);
    
            };
            // fn(1, 2);
            function fn() {}
        </script>
  4. 3, high-order functions

    A higher-order function
  • is a function that operates on other functions. It receives a function as a parameter or outputs a function as a return value
  • receives a function As a parameter
    <p></p>
    <script>
        // 高阶函数- 函数可以作为参数传递
        function fn(a, b, callback) {
            console.log(a + b);
            callback && callback();
        }
        fn(1, 2, function() {
            console.log(&#39;我是最后调用的&#39;);

        });

    </script>

Use the function as a return value

<script>
    function fn(){
        return function() {}
    }</script>

At this time fn is a higher-order function
  • The function is also a data type and can also be used as a parameter. Passed to another parameter for use. The most typical one is as a callback function
  • Similarly, the function can also be passed back as a return value
  • 4, closure

4.1, variable scope

Variables are divided into two types according to their scope: global variables and local variables

  1. 函数内部可以使用全局变量
  2. 函数外部不可以使用局部变量
  3. 当函数执行完毕,本作用域内的局部变量会销毁。

4.2、什么是闭包

闭包指有权访问另一个函数作用域中的变量的函数

简单理解:一个作用域可以访问另外一个函数内部的局部变量

    <script>
        // 闭包(closure)指有权访问另一个函数作用域中变量的函数。
        // 闭包: 我们fn2 这个函数作用域 访问了另外一个函数 fn1 里面的局部变量 num
        function fn1() {		// fn1就是闭包函数
            var num = 10;
            function fn2() {
                console.log(num); 	//10
            }
            fn2();
        }
        fn1();
    </script>

4.3、在chrome中调试闭包

  1. 打开浏览器,按 F12 键启动 chrome 调试工具。

  2. 设置断点。

  3. 找到 Scope 选项(Scope 作用域的意思)。

  4. 当我们重新刷新页面,会进入断点调试,Scope 里面会有两个参数(global 全局作用域、local 局部作用域)。

  5. 当执行到 fn2() 时,Scope 里面会多一个 Closure 参数 ,这就表明产生了闭包。

Detailed introduction to JavaScript to improve learning ES6

4.4、闭包的作用

  • 延伸变量的作用范围
    <script>
        // 闭包(closure)指有权访问另一个函数作用域中变量的函数。
        // 一个作用域可以访问另外一个函数的局部变量 
        // 我们fn 外面的作用域可以访问fn 内部的局部变量
        // 闭包的主要作用: 延伸了变量的作用范围
        function fn() {
            var num = 10;
            return function() {
                console.log(num);
            }
        }
        var f = fn();
        f();
    </script>

4.5、闭包练习

4.5.1、点击li输出索引号

    
            
  • 榴莲
  •         
  • 臭豆腐
  •         
  • 鲱鱼罐头
  •         
  • 大猪蹄子
  •     
    <script> // 闭包应用-点击li输出当前li的索引号 // 1. 我们可以利用动态添加属性的方式 var lis = document.querySelector(&#39;.nav&#39;).querySelectorAll(&#39;li&#39;); for (var i = 0; i < lis.length; i++) { lis[i].index = i; lis[i].onclick = function() { // console.log(i); console.log(this.index); } } // 2. 利用闭包的方式得到当前小li 的索引号 for (var i = 0; i < lis.length; i++) { // 利用for循环创建了4个立即执行函数 // 立即执行函数也成为小闭包因为立即执行函数里面的任何一个函数都可以使用它的i这变量 (function(i) { // console.log(i); lis[i].onclick = function() { console.log(i); } })(i); } </script>

Detailed introduction to JavaScript to improve learning ES6

4.5.2、定时器中的闭包

    
            
  • 榴莲
  •         
  • 臭豆腐
  •         
  • 鲱鱼罐头
  •         
  • 大猪蹄子
  •     
    <script> // 闭包应用-3秒钟之后,打印所有li元素的内容 var lis = document.querySelector(&#39;.nav&#39;).querySelectorAll(&#39;li&#39;); for (var i = 0; i < lis.length; i++) { (function(i) { setTimeout(function() { console.log(lis[i].innerHTML); }, 3000) })(i); } </script>

Detailed introduction to JavaScript to improve learning ES6

5、递归

如果一个函数在内部可以调用其本身,那么这个函数就是递归函数

简单理解: 函数内部自己调用自己,这个函数就是递归函数

由于递归很容易发生"栈溢出"错误,所以必须要加退出条件 return

    <script>
        // 递归函数 : 函数内部自己调用自己, 这个函数就是递归函数
        var num = 1;

        function fn() {
            console.log(&#39;我要打印6句话&#39;);

            if (num == 6) {
                return; // 递归里面必须加退出条件
            }
            num++;
            fn();
        }
        fn();
    </script>

6、浅拷贝和深拷贝

  1. 浅拷贝只是拷贝一层,更深层次对象级别的只拷贝引用
  2. 深拷贝拷贝多层,每一级别的数据都会拷贝
  3. Object.assign(target,....sources) ES6新增方法可以浅拷贝

6.1、浅拷贝

// 浅拷贝只是拷贝一层,更深层次对象级别的只拷贝引用var obj = {
    id: 1,
    name: 'andy',
    msg: {
        age: 18
    }};var o = {}for(var k in obj){
    // k是属性名,obj[k]是属性值
    o[k] = obj.[k];}console.log(o);// 浅拷贝语法糖Object.assign(o,obj);

6.2、深拷贝

// 深拷贝拷贝多层,每一级别的数据都会拷贝var obj = {
    id: 1,
    name: 'andy',
    msg: {
        age: 18
    }
    color: ['pink','red']};var o = {};// 封装函数function deepCopy(newobj,oldobj){
    for(var k in oldobj){
        // 判断属性值属于简单数据类型还是复杂数据类型
        // 1.获取属性值   oldobj[k]
        var item = obldobj[k];
        // 2.判断这个值是否是数组
        if(item instanceof Array){
            newobj[k] = [];
            deepCopy(newobj[k],item)
        }else if (item instanceof Object){
              // 3.判断这个值是否是对象
            newobj[k] = {};
            deepCopy(newobj[k],item)
        }else {
            // 4.属于简单数据类型
            newobj[k] = item;
            
        } 
    }}deepCopy(o,obj);

7、 正则表达式

正则表达式是用于匹配字符串中字符组合的模式。在JavaScript中,正则表达式也是对象。

正则表通常被用来检索、替换那些符合某个模式(规则)的文本,例如验证表单:用户名表单只能输入英文字母、数字或者下划线, 昵称输入框中可以输入中文(匹配)。此外,正则表达式还常用于过滤掉页面内容中的一些敏感词(替换),或从字符串中获取我们想要的特定部分(提取)等 。

7.1、特点

  • 实际开发,一般都是直接复制写好的正则表达式
  • 但是要求会使用正则表达式并且根据自身实际情况修改正则表达式

7.2、创建正则表达式

在JavaScript中,可以通过两种方式创建正则表达式

  1. 通过调用 RegExp 对象的构造函数创建

  2. 通过字面量创建

7.2.1、通过调用 RegExp 对象的构造函数创建

通过调用 RegExp 对象的构造函数创建

var 变量名 = new RegExp(/表达式/);

7.2.2、通过字面量创建

通过字面量创建

var 变量名 = /表达式/;

注释中间放表达式就是正则字面量

7.2.3、测试正则表达式 test

  • test()正则对象方法,用于检测字符串是否符合该规则,该对象会返回truefalse,其参数是测试字符串
regexObj.test(str)
  • regexObj 写的是正则表达式
  • str 我们要测试的文本
  • 就是检测str文本是否符合我们写的正则表达式规范

示例

    <script>
        // 正则表达式在js中的使用

        // 1. 利用 RegExp对象来创建 正则表达式
        var regexp = new RegExp(/123/);
        console.log(regexp);

        // 2. 利用字面量创建 正则表达式
        var rg = /123/;
        // 3.test 方法用来检测字符串是否符合正则表达式要求的规范
        console.log(rg.test(123));
        console.log(rg.test(&#39;abc&#39;));
    </script>

7.3、正则表达式中的特殊在字符

7.3.1、边界符

正则表达式中的边界符(位置符)用来提示字符所处的位置,主要有两个字符

边界符 说明
^ 表示匹配行首的文本(以谁开始)
$ 表示匹配行尾的文本(以谁结束)

如果^ 和 $ 在一起,表示必须是精确匹配

// 边界符 ^ $
var rg = /abc/;   //正则表达式里面不需要加引号,不管是数字型还是字符串型
// /abc/只要包含有abc这个字符串返回的都是true
console.log(rg.test('abc'));
console.log(rg.test('abcd'));
console.log(rg.test('aabcd'));

var reg = /^abc/;
console.log(reg.test('abc'));   //true
console.log(reg.test('abcd'));	// true
console.log(reg.test('aabcd')); // false

var reg1 = /^abc$/
// 以abc开头,以abc结尾,必须是abc

7.3.2、字符类

  • 字符类表示有一系列字符可供选择,只要匹配其中一个就可以了
  • 所有可供选择的字符都放在方括号内

①[] 方括号

/[abc]/.test('andy');     // true

后面的字符串只要包含 abc 中任意一个字符,都返回true

②[-]方括号内部 范围符

/^[a-z]$/.test()

方括号内部加上-表示范围,这里表示a - z26个英文字母都可以

③[^] 方括号内部 取反符 ^

/[^abc]/.test('andy')   // false

方括号内部加上^表示取反,只要包含方括号内的字符,都返回 false

注意和边界符 ^ 区别,边界符写到方括号外面

④字符组合

/[a-z1-9]/.test('andy')    // true

方括号内部可以使用字符组合,这里表示包含a 到 z的26个英文字母和1到9的数字都可以

    <script>
        //var rg = /abc/;  只要包含abc就可以 
        // 字符类: [] 表示有一系列字符可供选择,只要匹配其中一个就可以了
        var rg = /[abc]/; // 只要包含有a 或者 包含有b 或者包含有c 都返回为true
        console.log(rg.test(&#39;andy&#39;));
        console.log(rg.test(&#39;baby&#39;));
        console.log(rg.test(&#39;color&#39;));
        console.log(rg.test(&#39;red&#39;));
        var rg1 = /^[abc]$/; // 三选一 只有是a 或者是 b  或者是c 这三个字母才返回 true
        console.log(rg1.test(&#39;aa&#39;));
        console.log(rg1.test(&#39;a&#39;));
        console.log(rg1.test(&#39;b&#39;));
        console.log(rg1.test(&#39;c&#39;));
        console.log(rg1.test(&#39;abc&#39;));
        console.log(&#39;------------------&#39;);

        var reg = /^[a-z]$/; // 26个英文字母任何一个字母返回 true  - 表示的是a 到z 的范围  
        console.log(reg.test(&#39;a&#39;));
        console.log(reg.test(&#39;z&#39;));
        console.log(reg.test(1));
        console.log(reg.test(&#39;A&#39;));
        // 字符组合
        var reg1 = /^[a-zA-Z0-9_-]$/; // 26个英文字母(大写和小写都可以)任何一个字母返回 true  
        console.log(reg1.test(&#39;a&#39;));
        console.log(reg1.test(&#39;B&#39;));
        console.log(reg1.test(8));
        console.log(reg1.test(&#39;-&#39;));
        console.log(reg1.test(&#39;_&#39;));
        console.log(reg1.test(&#39;!&#39;));
        console.log(&#39;----------------&#39;);
        // 如果中括号里面有^ 表示取反的意思 千万和 我们边界符 ^ 别混淆
        var reg2 = /^[^a-zA-Z0-9_-]$/;
        console.log(reg2.test(&#39;a&#39;));
        console.log(reg2.test(&#39;B&#39;));
        console.log(reg2.test(8));
        console.log(reg2.test(&#39;-&#39;));
        console.log(reg2.test(&#39;_&#39;));
        console.log(reg2.test(&#39;!&#39;));
    </script>

7.3.3、量词符

量词符用来设定某个模式出现的次数

量词 说明
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
    <script>
        // 量词符: 用来设定某个模式出现的次数
        // 简单理解: 就是让下面的a这个字符重复多少次
        // var reg = /^a$/;


        //  * 相当于 >= 0 可以出现0次或者很多次 
        // var reg = /^a*$/;
        // console.log(reg.test(&#39;&#39;));
        // console.log(reg.test(&#39;a&#39;));
        // console.log(reg.test(&#39;aaaa&#39;));



        //  + 相当于 >= 1 可以出现1次或者很多次
        // var reg = /^a+$/;
        // console.log(reg.test(&#39;&#39;)); // false
        // console.log(reg.test(&#39;a&#39;)); // true
        // console.log(reg.test(&#39;aaaa&#39;)); // true

        //  ?  相当于 1 || 0
        // var reg = /^a?$/;
        // console.log(reg.test(&#39;&#39;)); // true
        // console.log(reg.test(&#39;a&#39;)); // true
        // console.log(reg.test(&#39;aaaa&#39;)); // false

        //  {3 } 就是重复3次
        // var reg = /^a{3}$/;
        // console.log(reg.test(&#39;&#39;)); // false
        // console.log(reg.test(&#39;a&#39;)); // false
        // console.log(reg.test(&#39;aaaa&#39;)); // false
        // console.log(reg.test(&#39;aaa&#39;)); // true
        //  {3, }  大于等于3
        var reg = /^a{3,}$/;
        console.log(reg.test(&#39;&#39;)); // false
        console.log(reg.test(&#39;a&#39;)); // false
        console.log(reg.test(&#39;aaaa&#39;)); // true
        console.log(reg.test(&#39;aaa&#39;)); // true
        //  {3,16}  大于等于3 并且 小于等于16
        var reg = /^a{3,6}$/;
        console.log(reg.test(&#39;&#39;)); // false
        console.log(reg.test(&#39;a&#39;)); // false
        console.log(reg.test(&#39;aaaa&#39;)); // true
        console.log(reg.test(&#39;aaa&#39;)); // true
        console.log(reg.test(&#39;aaaaaaa&#39;)); // false
    </script>

7.3.4、用户名验证

功能需求:

  1. 如果用户名输入合法, 则后面提示信息为 : 用户名合法,并且颜色为绿色
  2. 如果用户名输入不合法, 则后面提示信息为: 用户名不符合规范, 并且颜色为绿色

分析:

  1. 用户名只能为英文字母,数字,下划线或者短横线组成, 并且用户名长度为 6~16位.

  2. 首先准备好这种正则表达式模式 /$[a-zA-Z0-9-_]{6,16}^/

  3. 当表单失去焦点就开始验证.

  4. 如果符合正则规范, 则让后面的span标签添加 right 类.

  5. 如果不符合正则规范, 则让后面的span标签添加 wrong 类.

    <input> <span>请输入用户名</span>
    <script>
        //  量词是设定某个模式出现的次数
        var reg = /^[a-zA-Z0-9_-]{6,16}$/; // 这个模式用户只能输入英文字母 数字 下划线 短横线但是有边界符和[] 这就限定了只能多选1
        // {6,16}  中间不要有空格
        // console.log(reg.test(&#39;a&#39;));
        // console.log(reg.test(&#39;8&#39;));
        // console.log(reg.test(&#39;18&#39;));
        // console.log(reg.test(&#39;aa&#39;));
        // console.log(&#39;-------------&#39;);
        // console.log(reg.test(&#39;andy-red&#39;));
        // console.log(reg.test(&#39;andy_red&#39;));
        // console.log(reg.test(&#39;andy007&#39;));
        // console.log(reg.test(&#39;andy!007&#39;));
        var uname = document.querySelector(&#39;.uname&#39;);
        var span = document.querySelector(&#39;span&#39;);
        uname.onblur = function() {
            if (reg.test(this.value)) {
                console.log(&#39;正确的&#39;);
                span.className = &#39;right&#39;;
                span.innerHTML = &#39;用户名格式输入正确&#39;;
            } else {
                console.log(&#39;错误的&#39;);
                span.className = &#39;wrong&#39;;
                span.innerHTML = &#39;用户名格式输入不正确&#39;;
            }
        }
    </script>

7.4、括号总结

  1. 大括号 量词符 里面面表示重复次数
  2. 中括号 字符集合 匹配方括号中的任意字符
  3. 小括号 表示优先级
// 中括号 字符集合 匹配方括号中的任意字符
var reg = /^[abc]$/;
// a || b || c
// 大括号 量词符 里面表示重复次数
var reg = /^abc{3}$/;   // 它只是让c 重复3次 abccc
// 小括号 表示优先级
var reg = /^(abc){3}$/;  //它是让 abc 重复3次

在线测试正则表达式:https://c.runoob.com/

7.5、预定义类

预定义类指的是某些常见模式的简写写法

预定类 说明
\d 匹配0-9之间的任一数字,相当于[0-9]
\D 匹配所有0-9以外的字符,相当于[ ^ 0-9]
\w 匹配任意的字母、数字和下划线,相当于[A-Za-z0-9_ ]
\W 除所有字母、数字、和下划线以外的字符,相当于[ ^A-Za-z0-9_ ]
\s 匹配空格(包括换行符,制表符,空格符等),相当于[\t\t\n\v\f]
\S 匹配非空格的字符,相当于[ ^ \t\r\n\v\f]

7.5.1、表单验证

分析:

1.手机号码: /^1[3|4|5|7|8][0-9]{9}$/

2.QQ: [1-9][0-9]{4,} (腾讯QQ号从10000开始)

3.昵称是中文: ^[\u4e00-\u9fa5]{2,8}$

    <script>
        // 座机号码验证:  全国座机号码  两种格式:   010-12345678  或者  0530-1234567
        // 正则里面的或者 符号  |  
        // var reg = /^\d{3}-\d{8}|\d{4}-\d{7}$/;
        var reg = /^\d{3,4}-\d{7,8}$/;
    </script>

7.6、正则表达式中的替换

7.6.1、replace 替换

replace()方法可以实现替换字符串操作,用来替换的参数可以是一个字符串或是一个正则表达式

stringObject.replace(regexp/substr,replacement)
  1. 第一个参数: 被替换的字符串或者正则表达式
  2. 第二个参数:替换为的字符串
  3. 返回值是一个替换完毕的新字符串
// 替换 replacevar str = 'andy和red';var newStr = str.replace('andy','baby');var newStr = str.replace(/andy/,'baby');

7.6.2、正则表达式参数

/表达式/[switch]

switch按照什么样的模式来匹配,有三种

  • g: 全局匹配
  • i:忽略大小写
  • gi: 全局匹配 + 忽略大小写

相关推荐:javascript学习教程

The above is the detailed content of Detailed introduction to JavaScript to improve learning ES6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete