当前位置:   article > 正文

js手写数组push(),unshift(),pop(),shift(),map()方法_js手写unshift

js手写unshift

目录

1、push()

2、unshift()

3、pop()

4、shift()

5、map()


1、push()

  1. Array.prototype.push=function(){
  2. for(let i=0;i<arguments.length;i++){
  3. this[this.length]=arguments[i]
  4. }
  5. return this.length
  6. }
  7. const arr=[1,2,3]
  8. console.log(arr.push(4,5,6))

2、unshift()

  1. Array.prototype.unshift = function () {
  2. const args = [...arguments]
  3. const oldArray = [...this]
  4. for (let i = 0; i < args.length; i++) {
  5. this[i] = args[i]
  6. }
  7. for (let j = 0; j < oldArray.length; j++) {
  8. this[this.length] = oldArray[j]
  9. }
  10. return this.length
  11. }
  12. const arr = [1, 2, 3]
  13. console.log(arr.unshift(6, 5, 4))

3、pop()

  1. Array.prototype.pop=function(){
  2. if(this.length===0)return undefined
  3. const lastItem=this[this.length-1]
  4. this.length--
  5. return lastItem
  6. }
  7. const arr=[1,3,4]
  8. console.log(arr.pop())

4、shift()

  1. Array.prototype.shift=function(){
  2. if(this.length===0)return undefined
  3. const firstItem=this[0]
  4. for(let i=0;i<this.length;i++){
  5. this[i-1]=this[i]
  6. }
  7. this.length--
  8. return firstItem
  9. }
  10. const arr=[1,2,3]
  11. console.log(arr.shift())

5、map()

  1. Array.prototype.map=function(fn){
  2. const newArr=[]
  3. for(let i=0;i<this.length;i++){
  4. const r=fn(this[i],i,arr)
  5. newArr[newArr.length]=r
  6. }
  7. return newArr
  8. }
  9. arr=[8,5,7,9]
  10. console.log(arr.map(function(item){
  11. return item*2
  12. }))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/477071
推荐阅读
相关标签
  

闽ICP备14008679号