最佳答案
我在 map 和 foreach 中看到的唯一区别是,map
返回一个数组,而 forEach
不返回。然而,我甚至不理解 forEach
方法“ func.call(scope, this[i], i, this);
”的最后一行。例如,“ this
”和“ scope
”不是指同一个对象吗? this[i]
和 i
不是指循环中的当前值吗?
我注意到在另一篇文章中有人说: “当你想根据列表中的每个元素做某事时,使用 forEach
。例如,您可能正在向页面添加内容。从本质上说,这是伟大的时候,你想要“副作用”。我不知道副作用是什么意思。
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 中(因为我们没有更新数据库)除了像下面这样操作数字之外,还有什么实际用途吗?
alert([1,2,3,4].map(function(x){ return x + 1})); // This is the only example I ever see of map in JavaScript.