數組常用的源代碼

  1. push()
var arr = [1, 3, 4, 5]
	Array.prototype.myPush = function() {
		for(var i = 0; i < arguments.length; i ++) {
			this[this.length] = arguments[i]
		}
		return this.length
	}
	arr.myPush(1,34,5)
  1. pop
var arr = [1, 3, 4, 5]
	Array.prototype.myPop = function() {
		var num = this[this.length - 1]
		this.length --
		return num
	}
  1. reduce()
Array.prototype.myReduce = function(fn, init) {
		var i = 0,
			len = this.length,
			pre = init
		if (pre == undefined) {
			pre = this[i]
			i ++
		}

		for(i; i < len; i ++) {
			fn(pre, this[i], i)
		}
		return pre
	}
  1. forEach()
Array.prototype.myEach = function(fn) {
		console.log(this[0])
		var len = this.length
		for(var i = 0; i < len; i ++) {
			fn(this[i], i, this)
		}
	}
  1. filter()
Array.prototype.myFilter = function(fn) {
		var len = this.length,
			newArr = []
		for(var i = 0; i < len; i ++) {
			if(fn(this[i], i)) {
				newArr.push(this[i])
			}
		}
		return newArr
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章