js .map方法
2024-10-08 01:44:48
map
这里的map不是“地图”的意思,而是指“映射”。[].map(); 基本用法跟forEach方法类似:
array.map(callback,[ thisObject]);
callback的参数也类似: [].map(function(value, index, array) {
// ...
});
map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组。下面这个例子是数值项求平方:
var data = [1, 2, 3, 4]; var arrayOfSquares = data.map(function (item) {
return item * item;
}); alert(arrayOfSquares); // 1, 4, 9, 16
callback需要有return值,如果没有,就像下面这样: var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function() {}); arrayOfSquares.forEach(console.log);
结果,数组所有项都被映射成了undefined:
全部项都成了undefined
在实际使用的时候,我们可以利用map方法方便获得对象数组中的特定属性值们。例如下面这个例子(之后的兼容demo也是该例子):
var users = [
{name: "张含韵", "email": "zhang@email.com"},
{name: "江一燕", "email": "jiang@email.com"},
{name: "李小璐", "email": "li@email.com"}
]; var emails = users.map(function (user) { return user.email; }); console.log(emails.join(", ")); // zhang@email.com, jiang@email.com, li@email.com
Array.prototype扩展可以让IE6-IE8浏览器也支持map方法: if (typeof Array.prototype.map != "function") {
Array.prototype.map = function (fn, context) {
var arr = [];
if (typeof fn === "function") {
for (var k = 0, length = this.length; k < length; k++) {
arr.push(fn.call(context, this[k], k, this));
}
}
return arr;
};
}
最新文章
- ubuntu和win7 64双系统 安装
- 单片机温度控制系统DS18B20
- for循环与for循环嵌套
- 如何让您的php也支持pthreads多线程
- java 文件读取大全
- ASP.NET读取配置文件发送邮件
- 卸载RedHat7自带的yum,安装并使用网易163源
- 如何新建XCode项目
- 【劳动节江南白衣Calvin 】我的后端开发书架2015
- Android应用开发基础篇(8)-----SurfaceView
- Android 锁屏状态/锁屏密码等相关
- jquery 表格行计算
- Linux下安装与配置Nginx
- JAVA_SE基础——40.super关键字
- A Base Class pointer can point to a derived class object. Why is the vice-versa not true?
- analysed of J-SON/XML processing model Extend to java design model (J-SON/XML处理模型分析 扩展到Java设计模型 )
- Spark开发环境搭建(IDEA、Scala、SVN、SBT)
- python大法好——模块(内置模块未完)
- java基础之继承(一)
- ELK日志平台