Skip to content

Commit

Permalink
实现一些数组的方法
Browse files Browse the repository at this point in the history
  • Loading branch information
abstain23 committed Jun 12, 2020
1 parent 46fffe6 commit 000a70a
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 3 deletions.
2 changes: 1 addition & 1 deletion 专题系列/数组去重.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,4 @@ function unique(array) {

//es6最简单

let unique = (a) => [...new Set(a)]
let unique = (a) => [...new Set(a)]
1 change: 1 addition & 0 deletions 多文件上传测试/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
var chunkSize=2*1024*1024
var file = document.getElementById('file'), btn = document.getElementById('btn')
var formData = new FormData()
var chunks=[]
btn.addEventListener('click', () => {
var fileItem = file.files[0]
var blob = fileItem.slice(0, chunkSize)
Expand Down
64 changes: 62 additions & 2 deletions 数组一些常用的方法实现.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
Array.prototype.push = function() {
Array.prototype.forEach = function (cb, context = undefined) {
let arr = this.slice()
let len = arr.length
for (let i = 0; i < len; i++) {
if (i in arr) {
cb.call(context, arr[i], i, arr)
}
}
}

Array.prototype.push = function () {
for(let i = 0; i< arguments.length; i++) {
this[this.length] = arguments[i]
}
Expand All @@ -25,4 +35,54 @@ Array.prototype.shift = function() {
return value
}

Array.prototype.unshift =
Array.prototype.map = function (cb, context = undefined) {
let arr = this.slice()
let len = arr.length
let res = []
for (let i = 0; i < len; i++) {
res[i] = cb.call(context, arr[i], i, arr)
}
return res
}


Array.prototype.myReduce = function (cb, initData) {
let arr = this, len = arr.length
let res = initData || arr[0]
let startIndex = initData ? 0 : 1
for (let i = startIndex; i < len; i++) {
res = cb(res, arr[i], i, arr)
}
return res
}

Array.prototype.mapByReduce = function (cb, context = null) {
return arr.reduce((pre, curr, index, arr) => {
let res = cb.call(context, curr, index, arr)
return [...pre, res]
},[])
}

Array.prototype.filter = function (cb, context=undefined) {
let arr = this.slice()
let len = arr.length
let res = [], newIndex=0
for (let i = 0; i < len; i++) {
let flag = cb.call(context, arr[i], i, arr)
if (flag) {
console.log(i, flag)
res[newIndex++] = arr[i]
}
}
return res
}


Array.prototype.find = function (cb, context) {
let arr = this.slice()
let len = arr.length
for (let i = 0; i < len; i++) {
let res = cb.call(context, arr[i], i, arr)
if(res) return arr[i]
}
}

0 comments on commit 000a70a

Please sign in to comment.