ES6中forEach方法
来源:互联网 发布:信阳南湾鱼 知乎 编辑:程序博客网 时间:2024/09/21 06:36
本文引用地址:http://www.zhangxinxu.com/wordpress/?p=3220。感谢博主。
forEachforEach
是Array新方法中最基本的一个,就是遍历,循环。例如下面这个例子:
[1, 2 ,3, 4].forEach(alert);
等同于下面这个传统的for
循环:
var array = [1, 2, 3, 4];for (var k = 0, length = array.length; k < length; k++) { alert(array[k]);}
Array在ES5新增的方法中,参数都是function
类型,默认有传参,这些参数分别是?见下面:
[1, 2 ,3, 4].forEach(console.log);// 结果:// 1, 0, [1, 2, 3, 4]// 2, 1, [1, 2, 3, 4]// 3, 2, [1, 2, 3, 4]// 4, 3, [1, 2, 3, 4]
显而易见,forEach
方法中的function
回调支持3个参数,第1个是遍历的数组内容;第2个是对应的数组索引,第3个是数组本身。
因此,我们有:
[].forEach(function(value, index, array) { // ...});
对比jQuery中的$.each
方法:
$.each([], function(index, value, array) { // ...});
会发现,第1个和第2个参数正好是相反的,大家要注意了,不要记错了。后面类似的方法,例如$.map
也是如此。
现在,我们就可以使用forEach
卖弄一个稍显完整的例子了,数组求和:
var sum = 0;[1, 2, 3, 4].forEach(function (item, index, array) { console.log(array[index] == item); // true sum += item;});alert(sum); // 10
再下面,更进一步,forEach
除了接受一个必须的回调函数参数,还可以接受一个可选的上下文参数(改变回调函数里面的this
指向)(第2个参数)。
array.forEach(callback,[ thisObject])
例子更能说明一切:
var database = { users: ["张含韵", "江一燕", "李小璐"], sendEmail: function (user) { if (this.isValidUser(user)) { console.log("你好," + user); } else { console.log("抱歉,"+ user +",你不是本家人"); } }, isValidUser: function (user) { return /^张/.test(user); }};// 给每个人法邮件database.users.forEach( // database.users中人遍历 database.sendEmail, // 发送邮件 database // 使用database代替上面标红的this);// 结果:// 你好,张含韵// 抱歉,江一燕,你不是本家人// 抱歉,李小璐,你不是本家如果这第2个可选参数不指定,则使用全局对象代替(在浏览器是为window),严格模式下甚至是undefined.
另外,forEach不会遍历纯粹“占着官位吃空饷”的元素的,例如下面这个例子:
var array = [1, 2, 3];delete array[1]; // 移除 2alert(array); // "1,,3"alert(array.length); // but the length is still 3array.forEach(alert); // 弹出的仅仅是1和3
综上全部规则,我们就可以对IE6-IE8进行仿真扩展了,如下代码:
// 对于古董浏览器,如IE6-IE8if (typeof Array.prototype.forEach != "function") { Array.prototype.forEach = function (fn, context) { for (var k = 0, length = this.length; k < length; k++) { if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) { fn.call(context, this[k], k, this); } } };}
现在拿上面“张含韵”的例子测下我们扩展的forEach
方法,您可能狠狠地点击这里:兼容处理的forEach方法demo
例如IE7浏览器下:
阅读全文
0 0
- ES6中forEach方法
- ES6中forEach方法
- forEach循环es6语法
- ES6中 字符串中扩展 的方法
- c++中foreach的一种实现方法
- LINQ中ForEach方法的使用
- JavaScript 中 Array.forEach方法使用注意事项
- es6中Class的静态方法详解
- foreach方法
- es6 新增的map和foreach
- es6 新增的map和foreach
- C# foreach 中获取索引index的方法
- Unity中使用扩展方法解决foreach导致的GC
- php的foreach循环遍历嵌套html中方法
- C# foreach 中获取索引index方法的补充
- javascript中数组遍历方法forEach,every,some的区别
- JS中数组的常用方法(包含es6扩展)
- ES5和ES6中对于继承的实现方法
- C语言作业-9-1字符串比对
- 建站页面显示遇到的其它问题
- 颜色空间
- 学习网站分享
- D 03_js中正则对象和js数组对象
- ES6中forEach方法
- 关于Java中对于jsp文件的浅认识?
- 欢迎使用CSDN-markdown编辑器
- 架设属于自己的高性能Shadowsocks服务器
- 学习笔记——JAVA设计模式<17>访问者模式
- xshell的快捷键
- 各排序算法核心
- java正则表达式(详解)
- 使用Eclipse配置python环境并创建实例