它的JavaScript的forEach方法有什么用(即地图不能做)? [英] what use does the javascript forEach method have (that map can't do)?

查看:136
本文介绍了它的JavaScript的forEach方法有什么用(即地图不能做)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在地图和foreach看到的唯一区别是,地图将返回一个数组和的forEach 不是。但是,我甚至不明白的forEach 办法的最后一行 func.call(范围,这[一],我这) ; 。例如,是不是这个范围指的是同一个对象,而不是这[一] I 指的是在回路中的电流值?

The only difference I see in map and foreach is that map is returning an array and forEach is not. However, I don't even understand the last line of the forEach method "func.call(scope, this[i], i, this);". For example, isn't "this" and "scope" referring to same object and isn't this[i] and i referring to the current value in the loop?

我注意到另一个岗位有人说使用的forEach 当你想要做的列表中的每个元素的基础上的东西,你可能会添加东西到页面例如,从本质上讲,它是伟大的,当你想副作用。我不知道是什么副作用的意思。

I noticed on another post someone said "Use forEach when you want to do something on the basis of each element of the list. You might be adding things to the page, for example. Essentially, it's great for when you want "side effects". I don't know what is meant by side effects.

Array.prototype.map = function(fnc) {
    var a = new Array(this.length);
    for (var i = 0; i < this.length; i++) {
        a[i] = fnc(this[i]);
    }
    return a;
}

Array.prototype.forEach = function(func, scope) { 
    scope = scope || this; 
    for (var i = 0, l = this.length; i < l; i++) {
        func.call(scope, this[i], i, this); 
    } 
}

最后,是否有在JavaScript这些方法的任何实际用途(因为我们没有更新数据库)以外的其他操纵这样的数字:

Finally, are there any real uses for these methods in javascript (since we aren't updating a database) other than to manipulate numbers like this:

alert([1,2,3,4].map(function(x){ return x + 1})); //this is the only example I ever see of map in javascript.

感谢您的任何答复。

Thanks for any reply.

推荐答案

之间的最大区别地图的forEach 在你的问题中指定的是的forEach 原始数组元素进行操作。您(可能)改变原有的阵列中的每个元素。在另一方面,地图通过阵列上运行,应用功能,每一个元素,散发出结果作为的新的的数组。的副作用是原始数组被改变。

The big difference between map and forEach as specified in your question is that forEach operates on the original array elements. You are (potentially) changing each element in the original array. On the other hand, map is running through your array, applying a function to each element, and emitting the result as a new array. The "side effect" is that the original array is being changed.

这有没有涉及数据库(虽然现在有可能是,随着新的浏览器,HTML5等),并不意味着你不会有对数据结构进行操作的事实。阵列不仅可以包含数字,但DOM对象或其它任何东西。

The fact that there's no database involved (although now there could be, with newer browsers, HTML5, etc.) does not mean that you won't have to operate on data structures. Your array can contain not only numbers, but DOM objects or just about anything else.

这篇关于它的JavaScript的forEach方法有什么用(即地图不能做)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆