对js数组方法使用代码类似实现——持续补充

记录数组方法的同时,自己也想研究下用代码来类似实现数组的各种方法
数组方法使用请点击这里

源码地址:
https://github.com/v8/v8/blob/4.9-lkgr/src/js/array.js

JavaScript 不像 Java 一样,它提供的函数的源码并不是用本身自己这种语言编写的,而是用 C 或 C++ 写的。这些函数,其实只是一种对外公开的规范,就像是向开发提供的接口一样。所以严格讲,JavaScript 不是一门语言,而是一套规范,一套 API。
这与很多语言有着很大的不同。

对同一个函数,或者说同一个 API,也有多种不同的方式实现,因此,我们很难像 Java 一样查看 forEach 的源码,一个函数,在同一个版本,源码一致。

我们只能通过一些公开的参考一些浏览器内核公开代码,然后自己简单的实现一下

以下代码只做出了关键性代码处理,里面少了很多合理性判断,特殊处理等

push方法
Array.prototype.pushS= function(){
	 console.log(arguments)
	 // 这里的argumemnts是一个对应于传递给函数的参数的类数组对象
	 for(let i = 0;i < arguments.length; i++){
	   // 这里的this指的是调用该方法的数组
	   // 数组中最后一位元素的下标等于数组的长度减一,所有从this[this.length]位置开始将arguments的值插进去
	   this[this.length] = arguments[i]
	 }
	 // 返回新数组的长度
	 return this.length
}
let a = [1,2]
a.pushS(3,4)   // 返回数组的长度    4
console.log(a) // [1,2,3,4]
unshift方法

unshift()方法用于在数组的首位新增一个或多数据,并且返回操作后数组的长度

Array.prototype.unshiftS = function() {
  // ... 是es6的扩展运算符,不懂的童鞋可以去看下es6新特性
  let arr = [...arguments, ...this]
  for(let i = 0; i < arr.length; i++ ){
     // 循环赋值
     this[i] = arr[i]
  }
  return this.length
}

let a = [3,4]
a.unshiftS(1,2)  // 返回新数组的长度  4
console.log(a) // [1,2,3,4]
shift方法

删除并返回数组的第一个元素

Array.prototype.shiftS = function() {
  // ... 是es6的扩展运算符,不懂的童鞋可以去看下es6新特性
  if(this && this.length > 0){
    let a = this[0]
    this.reverse().pop()
    this.reverse()
    return a 
  }
}
let a= ['张三', '李四', '李四','赵五',  '赵五', '王麻子']
a.shiftS() // '张三'
console.log(a) ['李四', '李四','赵五',  '赵五', '王麻子']
forEach方法

Array.prototype.forEachS= function(fun) {
   for(let i = 0; i < this.length; i++){
      fun(this[i], i, this)
   }
} 
let a = [1,2,3]
let b = [4,5]
a.forEachS(function(item,index,arr){
  console.log(item,index,arr)
})
// 1 0 (3) [1, 2, 3]
// 2 1 (3) [1, 2, 3]
// 3 2 (3) [1, 2, 3]
filter方法
Array.prototype.filterS= function(fun) {
   let newArray = []
   for(let i = 0; i < this.length; i++){
      if(fun(this[i], i, this)){
        newArray.push(this[i])
	  }
   }
   return newArray
} 
// 数组去重
let a= ['张三', '李四', '李四','赵五',  '赵五', '王麻子']
let b = a.filterS((item,index,arr)=>{
   return arr.indexOf(item) === index  // 判断当前元素在数组中首次出现的位置是不是当前位置,返回符合条件的
 }) 
 console.log(b)  // ["张三", "李四", "赵五", "王麻子"]

map方法
Array.prototype.mapS= function(fun) {
   for(let i = 0; i < this.length; i++){
       this[i] =  fun(this[i], i, this)
   }
   return this
} 

let a= [1,2,3,4,5]
let b = a.mapS((item,index,arr)=>{
   return item + 2
 }) 
 console.log(b) // [3, 4, 5, 6, 7]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值