当前位置:网站首页>用JS函數形式實現一個Array.prototype.forEach(),.map(),.filter()
用JS函數形式實現一個Array.prototype.forEach(),.map(),.filter()
2022-04-21 07:15:00 【cornivores】
Array.prototype.forEach(),.map(),.filter()三者區別
- forEach(),map(),filter()三者都是實現對數組元素的迭代
- forEach(),map()兩者區別很小,唯一區別是forEach()無返回值,而map()有返回值,返回一個新的數組
- filter()返回經過函數篩選後的數組
Array.prototype.forEach()
用純粹的for循環寫出forEach的功效,forEach功效如圖所示:

實現代碼如下:
Array.prototype.forEach = function(callback, thisArg) {
//判斷第一個參數是否為函數
if(typeof callback != 'function') throw new TypeError(callback + 'must be a function')
var arr = this
//是否接收到了第二個參數
var thisValue = arguments[1] || this
for(let i = 0; i < arr.length; ++i) {
//改變this的指向
callback.call(thisValue, arr[i], i, arr)
}
}
Array.prototype.map()
map與forEach功效差不多,map功效如下:

代碼如下:
Array.prototype.map = function(callback, thisArg) {
//判斷第一個參數是否為函數
if(typeof callback != 'function') throw new TypeError(callback + 'must be a function')
var arr = this
//是否接收到了第二個參數
var thisValue = arguments[1] || this
//保存返回值
let returnValue = []
for(let i = 0; i < arr.length; ++i) {
//改變this的指向+推入返回值
if(callback.call(thisValue, arr[i], i, arr))
returnValue.push(arr[i])
}
return returnValue
}
Array.prototype.filter()
filter()功效如下:

代碼如下:
Array.prototype.filter = function(callback, thisArg) {
//判斷第一個參數是否為函數
if(typeof callback != 'function') throw new TypeError(callback + 'must be a function')
var arr = this
//是否接收到了第二個參數
var thisValue = arguments[1] || this
//保存返回值
let returnValue = []
for(let i = 0; i < arr.length; ++i) {
//該值符合原數組
if(callback.call(thisValue, arr[i], i, arr))
returnValue.push(arr[i])
}
return returnValue
}
版权声明
本文为[cornivores]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210615591393.html
边栏推荐
猜你喜欢
随机推荐
Learn SCI paper drawing skills (a)
JS 对象与字符串相互转换
学习瑞芯微RK3399pro记录(10)
Modify the launcher3 icon and add a mask or shadow icon to the icon
LEFT JOIN关联表中ON,WHERE后面跟条件的区别
毕业设计,课程环节学生成绩评价系统
Gojs anhydrous printing plate
[STM32 & LwIP] record the solution of a strange Ping failure
[STM32 H7] h743 notes on address distribution of each memory block
2. MySQL basic query
stm32mp157 wm8960音频驱动调试笔记
Code implementation of feature pyramid transformer
如何实现一个线程池隔离?
CISSP认证每日知识点(2022年4月14日)
Tensorflow foundation 0: file reading and storage
3. 事务和视图
JDBC简单实现学生管理系统
【ThreadX】ThreadX源碼閱讀計劃(二)
R language drawing | drawing mixed density function diagram and adding quantile line
Linux启动MySQL报错
![2、 3 [FPGA] how to light the LED](/img/3c/011e9314d99bb58f4234b831df544e.png)






![[SSM integration] 1 Basic environment construction](/img/f9/816e05e0246bcbfe101f64cf59fa5a.png)
