- some : 有一个满足条件则返回true,并停止遍历
Array.prototype.mySome = function(fn) {
for(let i = 0; i < this.length; i++) {
if(fn(this[i])) return true
}
return false
}
const handArr = [1,2,3,4,5]
const is = handArr.mySome((item) => {
return item < 4
})
console.log(is)
- every :全部满足则返回true
Array.prototype.myEvery = function(fn) {
for(let i = 0; i < this.length; i++) {
if(!fn(this[i])) return false
}
return true
}
const handArr = [1,2,3,4,5]
const is = handArr.myEvery((item) => {
return item < 6
})
console.log(is)
- filter :返回满足条件的数组
Array.prototype.myFilter = function(fn) {
const arr = []
for(let i = 0; i < this.length; i++) {
if(fn(this[i])) arr.push(this[i])
}
return arr
}
const handArr = [1,2,3,4,5]
const is = handArr.myFilter((item) => {
return item < 3
})
console.log(is)
- find :返回第一个符合条件的值,并停止遍历
Array.prototype.myFind = function(fn) {
for(let i = 0; i < this.length; i++) {
if(fn(this[i])) return this[i]
}
return undefined
}
const handArr = [1,2,3,4,5]
const is = handArr.myFilter((item) => {
return item < 4
})
console.log(is)
- forEach :遍历
Array.prototype.myForEach = function(fn) {
for(let i = 0; i < this.length; i++) {
// arr[i] = fn(this[i])
fn.call('window', this[i], i, this)
}
}
const handArr = [1,2,3,4,5]
handArr.myEvery((item) => {
console.log(item)
})
- map :返回计算之后的新数组
Array.prototype.myMap = function(fn) {
const arr = []
for(let i = 0; i < this.length; i++) {
// arr[i] = fn(this[i])
arr[i] = fn.call('window', this[i], i, this)
}
return arr
}
const handArr = [1,2,3,4,5]
const is = handArr.myMap((item) => {
return item * 2
})
console.log(is)
- sort :冒泡排序
Array.prototype.mySort = function(fn) {
for(let i = 0; i < this.length; i++) {
for(let j = 0; j < this.length - i; j++){
if(fn(this[j], this[j+1]) > 0) {
// let temp = this[j]
// this[j] = this[j+1]
// this[j+1] = temp
[this[j+1], this[j]] = [this[j], this[j+1]] //利用ES6解构交换两个数,更简单
}
}
}
return this
}
const handArr = [1,3,5,2,4]
const is = handArr.mySort((a, b) => {
return a-b
})
console.log(is)