ES6语法学习笔记

  • 箭头函数

    // ES6
    input.map(item => item + 1);
    
    // ES5
    input.map(function (item) {
      return item + 1;
    });
    
  • 定义常量/变量: const/let
    let声明的变量仅在作用域有效,不会提升

  • 解构赋值:

    数组结构:

    let [x, y] = [1, 2, 3];
    
    let [head, ...tail] = [1, 2, 3, 4];
    head // 1
    tail // [2, 3, 4]
    

    对象解构:

    let { foo, bar } = { foo: 'aaa', bar: 'bbb' };
    foo // "aaa"
    bar // "bbb"
    

    字符串解构:

    const [,,,,a] = 'type4';
    a // "4"
    

    函数参数解构:

    function add([x, y]){
      return x + y;
    }
    
    add([1, 2]); // 3
    

    解构使用默认值(当对象的属性值严格等于undefined的时候)

    	var {x, y = 5} = {x: 1};
    	x // 1
    	y // 5
    
  • 模板字符串
    用反引号(`)标识,模板字符串中嵌入变量,需要将变量名写在${}之中

    // 普通字符串
    `In JavaScript '\n' is a line-feed.`
    
    // 多行字符串
    `In JavaScript this is
     not legal.`
    
    console.log(`string text line 1
    string text line 2`);
    
    // 字符串中嵌入变量
    let name = "Bob", time = "today";
    `Hello ${name}, how are you ${time}?`
    
  • 字符串的新增方法

    判断字符串的方法,除开现有的indexOf,又新增了下列3个方法

    includes():返回布尔值,表示是否找到了参数字符串。
    startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
    endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

    新增的3个方法都支持第2个参数。

    let s = 'Hello world!';
    
    s.startsWith('world', 6) // true
    s.endsWith('Hello', 5) // true
    s.includes('Hello', 6) // false
    
    参数描述
    stringvalue必需,要查找的字符串。
    start 可选默认为 0。
    includes、startsWith设置从哪个位置开始查找
    endsWith是针对前n个字符

    repeat():repeat方法返回一个新字符串,表示将原字符串重复n次

    'x'.repeat(3) // "xxx"
    'hello'.repeat(2) // "hellohello"
    'na'.repeat(0) // ""
    

    padStart(),padEnd()
    如果某个字符串不够指定长度,会在头部或尾部补全。
    padStart()用于头部补全,padEnd()用于尾部补全。

    //生成 10 位的数值字符串
    '1'.padStart(10, '0') // "0000000001"
    '12'.padStart(10, '0') // "0000000012"
    '123456'.padStart(10, '0') // "0000123456"
    
    //提示字符串格式
    '12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
    '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
    

    trimStart(),trimEnd()
    它们的行为与trim()一致,trimStart()消除字符串头部的空格,trimEnd()消除尾部的空格。 返回的都是新字符串,不会修改原始字符串

  • Number.isInteger()

    Number.isInteger()用来判断一个数值是否为整数。

    Number.isInteger(25) // true
    Number.isInteger(25.1) // false
    
  • Math 对象的扩展
    Math.trunc方法用于去除一个数的小数部分,返回整数部分。

    Math.trunc(4.1) // 4
    Math.trunc(4.9) // 4
    Math.trunc(-4.1) // -4
    Math.trunc(-4.9) // -4
    Math.trunc(-0.1234) // -0
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值