本文摘自PHP中文网,作者V,侵删。

js原生方法map实现,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | <!DOCTYPE html>
<html>
<head>
<meta charset= "UTF-8" >
<meta name= "viewport" content= "width=device-width, initial-scale=1.0" >
<meta http-equiv= "X-UA-Compatible" content= "ie=edge" >
<meta name= "author" content= "杨欣" >
<title>map</title>
</head>
<body>
<script>
Array.prototype.my_map = function (callback) {
if (!Array.isArray( this ) || ! this .length || typeof callback !== 'function' ) {
return []
} else {
let result = [];
for (let index = 0; index < this .length; index++) {
const element = this [index];
result.push(callback(element, index, this ))
}
return result
}
}
let arr = [1, 2, 3, 4, 5]
let res = arr.my_map((ele, i) => {
return ele + 10
})
console.log(res)
</script>
</body>
</html>
|
(推荐教程:js教程)
补充知识点:
我们平时用的是已经封装好的map方法,如果让我们自己封装一个map,应该如何实现。
万变不离其宗,其实遍历数组的核心还是for循环。因此下面封装一个map方法。
思路如下:
1、在原型上添加一个方法
2、传一个函数和this
3、call 方法传的参数和封装好的map方法的参数是一样的。
1 2 3 4 5 6 7 8 9 | Array.prototype.fakeMap = function (fn,context) {
let arr = this ;
let temp = [];
for (let i=0;i<arr.length;i++){
let result = fn.call(context,arr[i],i,arr);
temp.push(result);
}
return temp;
}
|
推荐视频教程:javascript视频教程
以上就是js如何实现原生map的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
前端用nodejs能做什么
html怎么和js连接
javascript实现鼠标滚轮控制页面图片切换
详解json_decode出现空白的解决方法
解析js on及addeventlistener原理用法的区别
如何实现javascript延时加载
js怎么跳转到新页面?
如何判断网页中图片加载成功或者失败?
前端js怎么学
三分钟带你了解js和jsp的区别
更多相关阅读请进入《js》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » js如何实现原生map