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;
};
}

最新文章

  1. ubuntu和win7 64双系统 安装
  2. 单片机温度控制系统DS18B20
  3. for循环与for循环嵌套
  4. 如何让您的php也支持pthreads多线程
  5. java 文件读取大全
  6. ASP.NET读取配置文件发送邮件
  7. 卸载RedHat7自带的yum,安装并使用网易163源
  8. 如何新建XCode项目
  9. 【劳动节江南白衣Calvin 】我的后端开发书架2015
  10. Android应用开发基础篇(8)-----SurfaceView
  11. Android 锁屏状态/锁屏密码等相关
  12. jquery 表格行计算
  13. Linux下安装与配置Nginx
  14. JAVA_SE基础——40.super关键字
  15. A Base Class pointer can point to a derived class object. Why is the vice-versa not true?
  16. analysed of J-SON/XML processing model Extend to java design model (J-SON/XML处理模型分析 扩展到Java设计模型 )
  17. Spark开发环境搭建(IDEA、Scala、SVN、SBT)
  18. python大法好——模块(内置模块未完)
  19. java基础之继承(一)
  20. ELK日志平台

热门文章

  1. 《mysql必知必会》学习_第14章_20180806_欢
  2. Docker基础-使用Dockerfile创建镜像
  3. Navicat for MYSQL 断网时本地连接无法打开,2005错误
  4. EBS CAS SSO测试
  5. 详解Android中的四大组件之一:Activity详解
  6. LabVIEW(十二):VI本地化-控件标题内容的修改
  7. 使用cygwin中的awk工具进行mysql binlog日志查看[利刃篇]
  8. spring-boot(hello world)
  9. Testing - 软件测试知识汇总
  10. 4 spring 创建对象的三种方式