Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个Array.splice #103

Open
AwesomeDevin opened this issue Sep 19, 2023 · 0 comments
Open

实现一个Array.splice #103

AwesomeDevin opened this issue Sep 19, 2023 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

Array.prototype._splice = function(start, count, ...args){
    const arr = this  // 原数组 
    const res = [] // 结果
    const addArr = args // 添加的数据
    const changeIndexs = [] // 需要往后移动的下标

    if(!count) count = arr.length - start // count不存在时取 arr.length - start
    
    // 移动下标到最后
    const move = (index) => {
      const tmp = arr[index]
      for(let i = index;i<arr.length - 1; i++){
          arr[i] = arr[i+1]
      }
      arr[arr.length - 1] = tmp
    }
    
    for(let i = 0; i< count; i++){
        const startIndex = start + i
        res.push(arr[startIndex]) // 记录删除的结果
        changeIndexs.push(startIndex) // 记录需要移动的下标
    }
    for(item of changeIndexs){
        move(item)
    }
    
    arr.length = arr.length - res.length 
    return res
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant