javascript的高级用法(循环实现数组map方法)

javascript 复制代码
const selfMap =function(fn, context){
let arr = Array.prototype.slice.call(this)
let mappedArr = Array()
for(let i=0; i< arr.length; i++){
//skip empty item
if(!arr.hasOwnProperty(i));continue
mappedArr[i]= fn.call(contenxt, arr[i], i, this)
return mappedArr
}

使用方法:将selfMap注入到Array.prototype中(下面数组的迭代方法也是如此)

javascript 复制代码
Array.proptotype.selfMap=selfMap
[1,2,3].selfMap(number=> number * 2)

值得一提的是,map的第二个参数就是第一个参数回调中的这个点。如果第一个参数是箭头函数,则设置第二个 this 将无效,因为箭头函数的词法绑定。

另一个是稀疏数组的处理,HasOwnProperty 用于判断当前下标的元素是否存在于数组中,欢迎大家在评论区交流。

相关推荐
条tiao条21 小时前
不止语法糖:TypeScript Set 与 Map 深度解析
前端·javascript·typescript
froginwe1121 小时前
《WebPages 邮局》
开发语言
freewlt21 小时前
React Server Components 深度解析:从原理到实战的完整指南
前端·javascript·react.js
@insist12321 小时前
网络工程师-广域网与接入网技术(一):核心协议与流量控制
开发语言·网络·网络工程师·软考·软件水平考试
zhensherlock21 小时前
Protocol Launcher 系列:1Writer iOS 上的 Markdown 文档管理
javascript·笔记·ios·typescript·node.js·iphone·ipad
ˇasushiro1 天前
终端工具配置
开发语言·ios·swift
不写八个1 天前
PHP教程005:配置ThinkPHP环境
开发语言·php
迷海1 天前
C++内存对齐
开发语言·c++
炘爚1 天前
C++(流类:istream /ostream/istringstream /ostringstream)
开发语言·c++·算法