// forEach
Array.prototype.forEach = function(fn, context) {
if(Object.prototype.toString.call(fn) !== "[object Function]") {
throw new TypeError(fn + "is not a function");
}
for(let i = 0; i < this.length; i++) {
fn.call(context, this[i], i, this);
}
}
// map
Array.prototype.map = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
const arr = []
for (let i = 0; i < len; i++) {
arr.push(func.call(ctx, this[i], this))
}
return arr
}
// find
Array.prototype.find = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
let obj = undefined
for (let i = 0; i < len; i++) {
if (func.call(ctx, this[i], i)) {
obj = this[i]
}
}
return obj
}
// findIndex
Array.prototype.findIndex = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
let index = undefined
for (let i = 0; i < len; i++) {
if (func.call(ctx, this[i], i)) {
index = i
}
}
return index
}
// filter
Array.prototype.filter = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
const arr = []
for (let i = 0; i < len; i++) {
if (func.call(ctx, this[i], i)) {
arr.push(this[i])
}
}
return arr
}
// some
Array.prototype.some = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
let flag = false
for (let i = 0; i < len; i++) {
if (func.call(ctx, this[i], i)) {
flag = true
}
}
return flag
}
// every
Array.prototype.every = function (func, ctx) {
let len = this.length
if(Object.prototype.toString.call(func) !== "[object Function]") {
throw new TypeError(func + "is not a function")
}
let flag = true
for (let i = 0; i < len; i++) {
if (func.call(ctx, this[i], i)) {
flag = false
}
}
return flag
}
javascript数组方法(find,some,every...)实现
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 数组 一、数组的基本概念[https://gitee.com/xiaozhou_report/xiaozhou_f...
- 数组常用操作方法整理(包含es6)及详细使用。 1. every() 判断数组所有元素是否**全部**符合条件 返...
- 原理部分 JavaScript 在ES6版本后提供了一些更加便捷的方法供开发者使用,实现原理其实是在对应的构造函数...
- Array.prototype.pop() pop()[https://developer.mozilla.org...