ES 6配列方法ES 5実装、スロットルジッパー
2553 ワード
Array.prototype.join = function(arg) {
let result = this[0] || ''
const length = this.length
for (let i = 0; i< length; i++) {
result += arg + this[i]
}
return result
}
Array.prototype.slice = function(begin, end) {
let result = []
begin = begin || 0
end = end || this.length
for (let i = begin; i < end; i++) {
result.push(this[i])
}
return result
}
Array.prototype.forEach = function(fn) {
for (let i = 0; i < this.length; i++) {
if (i in this) {
fn.call(undefined, this[i], i, this)
}
}
}
Array.prototype.map = function(fn) {
let result = []
for (let i = 0; i < this.length; i++) {
if (i in this) {
result[i] = fn.call(undefined, this[i], i, this)
}
}
return result
}
Array.prototype.filter = function(fn) {
let result = []
let temp
for (let i = 0; i < this.length; i++) {
if (i in this) {
if (temp = fn.call(undefined, this[i], i, this)) {
result.push(temp)
}
}
}
return result
}
Array.prototype.reduce = function(fn, init) {
let result = init
for (let i = 0; i < this.length; i++) {
if (i in this) {
result = fn.call(undefined, result, this[i], i, this)
}
}
return result
}
a = [1, 2, 3, 4, 5]
const result1 = a.reduce( (result, item) => {return result + item}, 0)
const result2 = a.reduce( (result, item) => {return result + item}, 1)
console.log(result1)
console.log(result2)
var throttle = function(fn, time) {
let cd = false
return function() {
if (cd) {
return
}
fn.call()
cd = true
setTimeout(() => {
cd = false
}, time)
}
}
var debounce = function(fn, time) {
let timer = undefined
return function() {
if (timer !== undefined) {
window.clearTimeout(timer)
}
timer = setTimeout(() => {
fn.call()
timer = undefined
}, time)
}
}