Blogger Information
Blog 94
fans 0
comment 0
visits 91866
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
【JS】 js代码成员:变量-常量-函数总结
可乐随笔
Original
415 people have browsed it

JS代码成员:变量-常量-函数总结

一. 代码成员

  1. // 1.变量
  2. //末尾分号可选
  3. let username = '老马'
  4. //函数
  5. function getUserName(username){
  6. //函数体
  7. return 'Hello,' + username;
  8. }
  9. console.log('----------代码成员,1.变量;2.函数----------')
  10. //调用函数
  11. console.log(getUserName(username))
  12. username = '老李'
  13. console.log(getUserName(username))
  14. /**
  15. * * 1.变量:数据复用
  16. * * 2.函数: 操作复用
  17. */

二.字面量,变量与常量

1. 字面量

  1. '老马', 100, [1,2,3], {x:1, y:2}, function(){}

2. 变量

  1. //声明 + 赋值
  2. let a = 100;
  3. console.log('a = ',a)

3. 常量 const

  1. const USER_NAME = '老马'
  2. console.log('USER_NAME = ', USER_NAME)
  3. //更新 => 常量不能更新值
  4. //USER_NAME = '老李' 会报错!
  5. // ! let, const 用那个? 首选 const , 除非确定它会更新,比如循环

三. 函数

1. 命名函数

  1. //调用:在声明调用函数,成功了。说明函数声明提升到代码顶部
  2. //必须遵循“先声明,后使用”原则,声明提升违背了该原则
  3. //console.log(sum1(3,4))
  4. //声明
  5. function sum1(a,b){
  6. return '命名函数 a + b = ' + (a + b)
  7. }
  8. console.log(sum1(1,2))

2. 匿名函数

  1. //const, let 没有声明提升的效果
  2. // console.log(sum3(7, 8))
  3. //匿名函数符合先声明,后使用的原则,以后首选匿名函数
  4. const sum2 = function (a, b) {
  5. return '匿名函数 a + b = ' + (a + b)
  6. }
  7. console.log(sum2(7, 8))

3. 箭头函数

  1. //匿名函数的语法糖(简化)
  2. //语法:删除function, (...) => {...}
  3. let sum3 = (a, b) => {
  4. return '箭头函数 a + b = ' + (a + b)
  5. }
  6. console.log(sum3(10, 12))
  7. //继续简化,只有一条return,可不写{}和return
  8. sum3 = (a, b) => '箭头函数 a + b = ' + (a + b)
  9. console.log(sum3(10, 12))
  10. //只有一个参数,(...)也可不写
  11. sum3 = username => 'Hello,' + username
  12. console.log(sum3('老马'))
  13. //没有参数,(...)必须写
  14. sum3 = () => 'Hello,老李!'
  15. console.log(sum3())
  16. // _ 也是合法变量标识符
  17. sum3 = _ => 'Hello 老王!'
  18. console.log(sum3())
  19. // ! 箭头函数与匿名函数的最大区别:没有自己的this

4. 立即执行函数(IIFE)

  1. //一个语法,用(...)包住,就转为“表达式”,立即执行
  2. let res = (function (a, b) {
  3. return '立即执行函数 a + b = ' + (a + b)
  4. })(20,30)
  5. console.log(res)
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!