• slice,splice,substring,split


    slice

    const list = [1,2,3,4,5,6]
    
    console.log(list.slice(0,2)) // [1, 2]
    console.log(list.slice(0,-1)) //  [1, 2, 3, 4, 5]
    console.log(list.slice(-1)) // [6]
    console.log(list.slice(-1,-3)) // []
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1、前后两个参数代表起始位置和结束位置(不包含结束位置)
    2、大于0,从左到右,小于0从右到左计算位置
    3、如果只有一个参数,则默认截取到数组尾部
    4、第一个参数为负数时,不论第二个参数为何值,返回空数组(字符串为空字符串)
    5、不改变原数组

    splice

    const list = [1,2,3,4,5,6]
    
    console.log(list.splice(0,2)) // [1, 2]
    console.log(list.splice(0,0,6)) console.log(list) // []  // [6, 1, 2, 3, 4, 5, 6]
    console.log(list.slice(0,-1)) //  [1, 2, 3, 4, 5]
    console.log(list.splice(-1)) // [6]
    console.log(list.splice(-1,-3)) // []
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1、只能数组使用
    2、三个参数按顺序分别代表起始位置、删除数量、需要添加的新元素,第二位为0是代表添加
    3、大于0,从左到右,小于0从右到左计算位置
    4、如果只有一个参数,则默认截取到数组尾部
    5、会改变原数组

    substring

    const str = '123456'
    
    console.log(str.substring(0,2)) // '12'
    console.log(str.substring(2,0)) // '12'
    console.log(str.substring(0,-1)) //  ''
    console.log(str.substring(-1)) // '123456'
    console.log(str.substring(-1,-3)) // ''
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1、只能字符串使用
    2、前后两个参数代表起始位置和结束位置(不包含结束位置)
    3、前后两个参数大小不要求,会自动从数值小的参数开始
    4、负值会默认转为0
    5、如果只有一个参数,则默认截取到字符串尾部
    6、不会改变原字符串

    split

    const str = 'hello world !'
    
    console.log(str.split()) // ['hello world !']
    console.log(str.split('')) // ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', ' ', '!']
    console.log(str.split(' ')) // ['hello', 'world', '!']
    console.log(str.split('world')) // ['hello ', ' !']
    console.log(str.split('world',1)) // ['hello ']
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    1、第一个参数代表字符串或正则表达式,从该参数指定的地方分割,第二个参数代表返回数组最大长度
    2、只能字符串使用

  • 相关阅读:
    Leetcode3042. 统计前后缀下标对 I
    Linux (一) 基础复习
    MFC 使用 Imm 类库实现输入法修改输入模式的技术文档
    单片机根据应答发送AT指令控制ESP8266设置为服务器—AP模式
    Java NIO 通信基础
    CentOS7 硬盘扩容
    C语言可变参数函数及其实现
    6 种方式读取 Springboot 的配置,老鸟都这么玩(原理+实战)
    Jupyter notebook无法显示pyecharts
    Milvus向量数据库检索
  • 原文地址:https://blog.csdn.net/qq_37768929/article/details/126866389