美文网首页
es6提供的好用方法

es6提供的好用方法

作者: 小小的开发人员 | 来源:发表于2019-04-24 10:24 被阅读0次

    【是否包含字符串】
      传统上,JS只有indexOf才可以确定一个字符串是否包含在另一个字符串中,es6又提供了3种新方法。

    • includes(),返回true/false,表示是否找到了参数字符串
    • startsWith(),返回true/false,表示参数字符串是否在源字符串的头部
    • endsWith,返回true/false,表示参数字符串是否在源字符串的尾部
    let str = "123"
    str.includes('12')
    true
    str.startsWith('1')
    true
    str.startsWith('h')
    false
    str.startsWith('')
    true
    str.endsWith('3')
    true
    str.endsWith('2')
    false
    str.endsWith('')
    true
    

    这3个方法都支持第二个参数,表示开始搜索的位置。

    【字符串补全长度】

    • padStart(),如果字符串不够指定长度,会在头部/尾部进行补全。
    • padEnd(),如果字符串不够指定长度,会在头部/尾部进行补全。
    let str = '123'
    str.padStart(10,'x')
    "xxxxxxx123"
    str.padEnd(10,'x')
    "123xxxxxxx"
    str.padStart(10,'ab')
    "abababa123"
    str.padEnd(10,'ab')
    "123abababa"
    str.padEnd(10) // 如果省略第二个参数,则会用空格补全
    "123       "
    str.padStart(10) 
    "       123"
    str.padStart(10, '123456789')  // 如果补全的字符串与原字符串之后超过了指定里的最小长度,则会截去超过位数的补全字符串
    "1234567123"
    

    padStart的常用是为数值补全指定位数。

    '1'.padStart(10,'0')
    "0000000001"
    '12'.padStart(10, 'YYYY-MM-DD')
    "YYYY-MM-12"
    

    【数组】

    • includes(),返回true/false,用法同字符串
    • find(),找到第一个符合条件的数组成员,如果所有成员都不符合条件,则返回undefined
    • findIndex,找到第一个符合条件的数组成员的位置,如果所有成员都不符合条件,则返回-1
    [1, 5, 10, 15].find(function (item, index, arr) {
      return item > 10
    })
    15
    
    [1, 5, 10, 15].findIndex(function (item, index, arr) {
      return item > 10
    })
    2
    

    相关文章

      网友评论

          本文标题:es6提供的好用方法

          本文链接:https://www.haomeiwen.com/subject/yzkwgqtx.html