当前位置:网站首页>【重构map】【重构filter】【重构Some】【重构reduce方法】【重构flat函数】
【重构map】【重构filter】【重构Some】【重构reduce方法】【重构flat函数】
2022-08-08 11:53:00 【勇敢*牛牛】
重构map
var arr = [1,3,4,5,5];
Array.prototype.myMap = function(callback,item){
var arr = [];
for(var i=0;i<this.length;i++){
var temp = callback(this[i],i,this);
arr.push(temp);
}
return arr;
}
arr = arr.myMap(function(item,index){
return item*2
})
console.log(arr);//[2, 6, 8, 10, 10]
</script>
重构filter
Array.prototype.myFilter = function(callback){
var arr = [];
for(var i=0;i<this.length;i++){
if(callback(this[i],i,this)){
arr.push(this[i]);
}
}
return arr
}
arr = arr.myFilter(function(item){
return item > 3
})
console.log(arr);//[4, 5, 5]
重构Some
Array.prototype.mySome = function(callback){
var arr = [];
for(var i=0;i<this.length;i++){
if(callback(this[i])){
return true;
}
}
return false
}
arr = arr.mySome(function(item){
return item > 7
})
重构reduce方法
arr = [1, 2, 3]
Array.prototype.myReduce = function (callback, init) {
var start = init === undefined ?1:0;
init = init ?? this[0];
for (var i = start; i < this.length; i++) {
var init = callback(init, this[i])
}
return init;
}
var sulter = arr.myReduce(function (v, t) {
return v + t;
},2)
console.log(sulter);
重构flat函数
Array.prototype.myFlat = function(depth = 1){
if(depth == 0) return this;
console.log('this=',this);
return this.reduce((v,t)=>{
if(Array.isArray(t)){
return [...v,...t.myFlat(depth-1)]
}else{
return [...v,t]
}
},[])
}
arr= [1,2,3,3,[36,9,9,[0]]]
arr = arr.myFlat()
console.log(arr);//[1, 2, 3, 3, 36, 9, 9, Array(1)]
边栏推荐
- ets declarative ui development, how to get the current system time
- 微服务负载均衡器LoadBalancer实战
- office安装出现了“office对安装源的访问被拒绝30068-4(5)”错误
- STM32的内存管理相关(内存架构,内存管理,map文件分析)
- DDoS攻击为什么是无解的
- 微服务负载均衡器Ribbon实战
- About the Celery service report under win Process 'Worker' exited with 'exitcode 1' [duplicate]
- shell之常用小工具
- 【Force】Add two numbers
- MYSQL 的 MASTER到MASTER的主主循环同步
猜你喜欢
随机推荐
一文读懂配置管理(CM)
IJCAI 2022 | 基于随机游走聚合的图神经网络
.NET Community Toolkit 8.0.0 版本发布
搞清楚系统到底怎样支撑高并发以及架构图的绘制(面试向)
Mobile adaptation method of vw/vh - vw/vh instance - analog B stand mobile home page - get style tutorial video
leetcode:761. 特殊的二进制序列【递归 + 转换有效括号】
【C语言】[编程题]倒置字符串
TF-GNN踩坑记录(一)
分分钟快速定制您的专属个性化软件应用——BizTool自动化工具简介
轻量级接口自动化框架(jmeter+ant+jenkins)
探究!一个数据包在网络中的心路历程
测试开发专栏——序言:总结过去,展望未来
结合“xPlus”探讨软件架构的创新与变革
MySQL----索引
消防安全知识培训讲座
无心剑2022年七绝100首
EZVIZ and Xiaomi compete against smart cameras
一文读懂配置管理(CM)
vim /etc/profile 写入时 出现 E121:无法打开并写入文件解决方案
硬盘数据恢复工具









