every 原理
使用 for 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._every = function (callback) {
for (let i = 0; i < this.length; i++) {
if(!callback(this[i], i, this)) return false
}
return true
}
const flag = array._every((value, index, array) => {
return value !== '入间同学'
})
console.log(flag)
使用 for in 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._every = function (callback) {
for (const key in this) {
if('NaN' === (+key + '')) return true
if(!callback(this[key], key, this)) return false
}
return true
}
const flag = array._every((value, index, array) => {
return value !== '蝶祈'
})
console.log(flag)
some 原理
使用 for 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._some = function (callback) {
for (let i = 0; i < this.length; i++) {
if(callback(this[i], i, this)) return true
}
return false
}
const flag = array._some((value, index, array) => {
return value === '入间同学'
})
console.log(flag)
使用 for in 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._some = function (callback) {
for (const key in this) {
if('NaN' === (+key + '')) return false
if(callback(this[key], key, this)) return true
}
return false
}
const flag = array._some((value, index, array) => {
return value === '入间同学'
})
console.log(flag)
find 原理
使用 for 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._find = function (callback) {
for (let i = 0; i < this.length; i++) {
if(callback(this[i], i, this)) return this[i]
}
return undefined
}
const res = array._find((value, index, array) => {
return value === '入间同学'
})
console.log(res)
使用 for in 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._find = function (callback) {
for (const key in this) {
if('NaN' === (+key + '')) return undefined
if(callback(this[key], key, this)) return this[key]
}
return undefined
}
const res = array._find((value, index, array) => {
console.log(value)
return value === '入间同学'
})
console.log(res)
findIndex 原理
使用 for 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._findIndex = function (callback) {
for (let i = 0; i < this.length; i++) {
if(callback(this[i], i, this)) return i
}
return -1
}
const res = array._findIndex((value, index, array) => {
return value === '蝶祈'
})
console.log(res)
使用 for in 实现
const array = ['稚名真白', '樱岛麻衣', '蝶祈']
Array.prototype._findIndex = function (callback) {
for (const key in this) {
if('NaN' === +key + '') return -1
if(callback(this[key], +key, this)) return +key
}
return -1
}
const res = array._findIndex((value, index, array) => {
return value === '蝶祈'
})
console.log(res)