常见的几种JS语法糖

语 法 糖

语法糖(Syntactic sugar),也译为糖衣语法。指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。

通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。

语法糖”可以给我们带来方便,是一种便捷的写法,编译器会帮我们做转换;而且可以提高开发编码的效率,在性能上也不会带来损失。

那么,下面来学习几种常见的【JS语法糖】吧

1、对象字面量
let sex1 = 'man', sex2 = ‘woman’
let sex = {man,woman}  

2、箭头函数
let fun = function(params){}
//可以缩写成如下 箭头函数会改变this的指向
let fun= params =>{}
//当参数有两个及以上时,如下:
let fun= (params1,params2,,,)=>{}


3、数组解构
let arr = ['a','b','c'];
let {a,b} = arr
console.log(a) // a
//数组解构也允许你跳过你不想用到的值,在对应地方留白即可,举例如下
let {a,,c} = array
console.log(c)  //c
 
4、函数默认参数
function  getResponse(a,b=0) {
  //常用于请求数据时,设置默认值 
}
 
5、拓展运算符
function test() {
  return [...arguments]
}
test('a', 'b', 'c') // ['a','b','c']
//扩展符还可以拼合数组
 let all = ['1',...['2','3'],...['4','5'],'6']   // ["1", "2", "3", "4", "5", "6"]
 
6、模板字符串
let id = ' 菜鸟'
let blog = '博主id是:${a}' // 博主id是:
1
7、多行字符串
//利用反引号实现多行字符串(虽然回车换行也是同一个字符串)
let poem = `A Pledge
    By heaven,
    I shall love you
    To the end of time!
    Till mountains crumble,
    Streams run dry,
    Thunder rumbles in winter,
    Snow falls in summer,
    And the earth mingles with the sky —
    Not till then will I cease to love you!`

8、拆包表达式
const data = {
      a: 'a',
      b: 'b',
      c: 'c'
}
let {a,c} = data
console.log(c); // c 
 
9、ES6中的类
class helloJs{
// 构造方法
  constructor(options = {}, data = []) { 
        this.name = ' 菜鸟'
        this.data = data
        this.options = options
    }
 // 成员方法
    getName() { 
        return this.name
    }
}

10、模块化开发
// 新建一个util.js 文件夹
let formatTime = date=>{
    ....
}
let endTime = date=>{
    ....
}

module.exports = {
   formatTime,
   endTime,
}
//可以用import {名称} from '模块' 
//然后再同级目录创建一个js文件 引入 util.js
//import {endTime} from 'util'
//或者全部引入
//import util from 'util'

以上就是JS常见的语法糖的介绍了

猜你喜欢

转载自blog.csdn.net/weixin_44821114/article/details/132956197