Blogger Information
Blog 40
fans 0
comment 1
visits 34291
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
JavaScript初学习之常量、变量、函数、匿名函数、箭头函数、闭包、高阶函数和立即执行函数认识与使用
景云
Original
612 people have browsed it

JavaScript 初学习

  1. 序:
  2. 0.1 js是前端通用的脚本语言
  3. 0.2 分为内联脚本(写在事件属性总)、内部脚本(写在script中)、外部脚本(写在script:src属性中)

1.常量

  1. 1.1 使用const进行声明
  2. // 常量声明时就需赋值,后续不可更新
  3. const num=888;

2.变量

  1. 2.1 使用let进行声明
  2. // 变量声明
  3. let userName;
  4. // 声明并赋值
  5. let userName2="景云";
  6. // 更新
  7. userName2="景云 Plus";

变量和常量只能用字母、数字(不能以数字开头)、下划线;严格区分大小写;不得使用关键字可保留字。

3.函数

  1. 3.1 会被自动提升到顶部;可以被重写
  2. 3.2 函数的参数
  3. //其中a和b为必选参数
  4. let sum=function(a,b){
  5. return a+b;
  6. }
  7. console.log(sum(1,2));//结果为3
  8. // 可设置默认参数b
  9. sum=function(a,b=3){
  10. return a+b;
  11. }
  12. console.log(sum(1));//结果为4
  13. sum=function(a,b,c,d){
  14. return a+b+c+d;
  15. }
  16. console.log(sum(1,2,3,4));//结果为10
  17. // 归内参数:可将上面类似的函数简化其参数声明
  18. sum=function(...arr){
  19. return arr.reduce(function(a,z){
  20. return a+z;
  21. });
  22. }
  23. console.log(sum(1,22,3,4));//结果为30
  24. let params=[1,22,3,4];
  25. //扩展参数:...,用来简化函数的调用参数
  26. console.log(sum(...params));//结果为30
  27. 3.3 函数的返回值
  28. 函数的返回值都是单值,如果想返回多个值,可将结果封装到数组或对象中
  29. let getItems=function(){
  30. return [100,'phone',2333];
  31. }
  32. console.log(getItems());
  33. getItems=function(){
  34. return {id:100,name:'phone',price:2333};
  35. }
  36. console.table(getItems());

4.匿名函数

  1. 不可以提升;声明为常量即不可重写

5.箭头函数:用来简化匿名函数的声明,只有匿名函数才能用箭头函数

  1. // 将3.2中的sum函数改为箭头函数
  2. sum=(a,b)=>{
  3. return a+b;
  4. }
  5. console.log(sum(100,200));
  6. // 如果函数体只有一条语句,可不写return
  7. sum=(a,b)=> a+b;
  8. console.log(sum(100,200));
  9. // 只有一个参数,小括号也可以不写
  10. sum=a=> console.log(a);
  11. sum("aaa");
  12. // 如果没有参数,小括号不可以省略
  13. sum=()=>console.log("sss");
  14. sum();

6.闭包:能够访问自由变量的函数,理论上讲任何函数都是闭包。

  1. 例子,其中num为自由变量,b为参数变量,c为私有变量。
  2. let num=20;
  3. function a(b){
  4. let c=100;
  5. return b+c+num;
  6. }

7.高阶函数:使用函数为参数或者将函数作为返回值的函数

  1. 7.1 回调函数
  2. 7.2 偏函数:简化了声明时的参数声明
  3. 7.3 纯函数:完全独立于调用上下文,返回值只能受到传入的参数影响

8.立即执行函数 IIFE :声明完直接调用

  1. function sum2(a,b){
  2. console.log(a+b);
  3. }
  4. sum2(10,210);
  5. // 将上面的函数修改为立即执行函数
  6. (function(a,b){
  7. console.log(a+b);
  8. })(20,30);
Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!