forEach in JavaScript
forEach in JavaScript
有人可以向我深入解释forEach
如何在JavaScript中工作,它做什么以及如何使用它吗?我所知道的是,它是一种使用函数和数组的循环。我理解其他循环,如for
、while
、do-while
和for-in
,但我就是无法理解forEach
循环。我已经尝试了其他在线资源,但我仍然很迷茫,不知道它的作用以及如何正确"创建"一个,因为我不明白语法。一些帮助将不胜感激。谢谢
> Array.prototype.forEach
是一个函数,它遍历数组中的所有项目,执行第一个参数中定义的回调函数。语法如下所示:
Array.forEach(function(currentValue, index, array) {}, thisArg);
函数内部是执行什么代码,回调函数的参数如下: currentValue, currentIndex, arrayThatWasCalledOn
它通常用于循环遍历长数组。第二个参数是thisArgument
,此参数设置为的任何值都是函数作用域内相应的 this
关键字。
Array.forEach(function() {console.log(this.name);}, {name: "value"});
请注意,一旦循环启动,break
语句就不能用于退出循环。这就是建议使用 for 循环的原因。
下面是一个代码示例:
var fruits = ["lemon", "apple", "orange", "lettuce"];
fruits.forEach(function(currentFruit) {
if (isFruit(currentFruit) === false) {
console.log("Error: Item is not a fruit!");
}
}
理解forEach方法的最佳方法是从头开始创建它。forEach 原生 Javascript 函数基本上是一个内部有一个循环的函数,它将使用迭代器函数(回调)对集合中的每个项目(集合可以是数组或对象)执行。
前任:
var forEach = function(collection, iterator) {
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
iterator(collection[i], i, collection);
}
} else {
for (var key in collection) {
iterator(collection[key], key, collection);
}
}
};
现在,如果您调用传递集合和迭代器的 forEach 函数,它应该记录集合中的每个名称:
// This is your collection
var names = ['John', 'Robert', 'James'];
// This is the action that you want to perform on each item
var action = function(item) {
console.log(item);
}
// Now you execute the forEach function passing the collection and the iterator and it should log each name from the collection.
forEach(names, action); // Logs -> 'John' 'Robert' 'James'
原生的forEach函数和我们刚刚创建的forEach函数之间的主要区别在于,你不需要将集合传递给它,因为Javascript将使用实际的对象(名称)作为你将迭代的集合。
names.forEach(action); // Logs -> 'John' 'Robert' 'James'
为了深入了解这个主题,我建议您阅读Eloquent Javascript书籍中的函数式编程章节
。我希望它有所帮助。
for each ...in 语句已弃用为 ECMA-357 (E4X) 标准的一部分。E4X 支持已被删除,但对于每个...由于向后兼容性考虑,不会禁用和删除 in。考虑用于...的。
例:
var sum = 0;
var obj = {prop1: 5, prop2: 13, prop3: 8}; /* obj array with properties and values */
for each (var item in obj) {
sum += item;
}
console.log(sum);
日志 "26",即 5+13+8,这里的 var 将迭代对象的 prop 值,例如 5,13,8...等,
这种循环在Java脚本中的一个重要用途是你不必关心数组或对象数组的索引,无论是数字还是字符串,Loop都会迭代!这在迭代对象中非常有用。
- onclick javascript in PHP
- javascript in jquery popup
- Javascript in Visual studio Web Api
- JavaScript in WebView - Android Studio
- JavaScript in Netbeans
- openDatabaseSync in Javascript in QT-Quick
- Javascript in partial (Ruby on Rails)
- javascript in onkeypress value
- 如何从 javascript in html 访问 Java 中的方法
- javascript in onXXX handler escaping of & in parameter
- Bootstrap3 remote modal with javascript in remote?
- Javascript in foreach Magento
- Indy TIdHTTPServer OnCommandGet javascript in html not execu
- Html and javascript in visual studio 2013
- JavaScript in AJAX Response
- JavaScript in SQL
- popover javascript in foreach php
- Javascript in Asp.net,C#
- JavaScript in HTML head, innerhtml 不起作用
- Load HTML with javaScript in <a href...> link