// 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...)實現
?著作權歸作者所有,轉載或內容合作請聯系作者
- 文/潘曉璐 我一進店門蒂破,熙熙樓的掌柜王于貴愁眉苦臉地迎上來馏谨,“玉大人,你說我怎么就攤上這事附迷【寤ィ” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵喇伯,是天一觀的道長喊儡。 經常有香客問我,道長稻据,這世上最難降的妖魔是什么艾猜? 我笑而不...
- 文/花漫 我一把揭開白布低淡。 她就那樣靜靜地躺著,像睡著了一般瞬项。 火紅的嫁衣襯著肌膚如雪蔗蹋。 梳的紋絲不亂的頭發(fā)上,一...
- 文/蒼蘭香墨 我猛地睜開眼涮较,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了冈止?” 一聲冷哼從身側響起狂票,我...
- 正文 年R本政府宣布跟衅,位于F島的核電站孵睬,受9級特大地震影響,放射性物質發(fā)生泄漏与斤。R本人自食惡果不足惜肪康,卻給世界環(huán)境...
- 文/蒙蒙 一荚恶、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧磷支,春花似錦谒撼、人聲如沸。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至善榛,卻和暖如春辩蛋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背移盆。 一陣腳步聲響...
推薦閱讀更多精彩內容
- 數組 一、數組的基本概念[https://gitee.com/xiaozhou_report/xiaozhou_f...
- 數組常用操作方法整理(包含es6)及詳細使用。 1. every() 判斷數組所有元素是否**全部**符合條件 返...
- 原理部分 JavaScript 在ES6版本后提供了一些更加便捷的方法供開發(fā)者使用畔派,實現原理其實是在對應的構造函數...
- 前言 在開發(fā)中铅碍,數組的使用場景非常多,平日中也涉及到很多數組的api/相關操作线椰,一直也沒有對這塊內容進行一塊整理總...