词条 | Foreach loop | ||||||||||
释义 |
For each (or foreach, sometimes called an iterative for-loop) is a control flow statement for traversing items in a collection. Foreach is usually used in place of a standard for statement. Unlike other for loop constructs, however, foreach loops[1] usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal. The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in the collection concurrently. SyntaxSyntax varies among languages. Most use the simple word for each item in collection: do something to item Language supportProgramming languages which support foreach loops include ABC, ActionScript, Ada, C++11, C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), ECMAScript, Erlang, Java (since 1.5, using the reserved word Ada{{Wikibooks|Ada Programming|Control}}Ada supports foreach loops as part of the normal for loop. Say X is an array: This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed. Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...): CThe language C does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro. However, two obvious problems occur:
C string as a collection of char C int array as a collection of int (array size known at compile-time) Most general: string or array as collection (collection size known at run-time) Note: idxtype can be removed and typeof(col[0]) used in its place with GCC C#In C#, assuming that myArray is an array of integers: Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression: C++C++11 provides a foreach loop. The syntax is similar to that of Java: C++11 range-based for statements have been implemented in GNU Compiler Collection (GCC) (since version 4.6), Clang (since version 3.0) and Visual C++ 2012 (version 11 [2]) The range-based for is syntactic sugar equivalent to: The compiler uses argument-dependent lookup to resolve the begin and end functions.[3] The C++ Standard Library also supports for_each,[4] that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the beginning to the end, the range and direction you can change the direction or range by altering the first two parameters. Qt, a C++ framework, offers a macro providing foreach loops[5] using the STL iterator interface: Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:[6]C++/CLIThe C++/CLI language proposes a construct similar to C#. Assuming that myArray is an array of integers: ColdFusion Markup Language (CFML){{Main|ColdFusion Markup Language}}Script syntaxTag syntaxCFML incorrectly identifies the value as "index" in this construct; the Common LispCommon Lisp provides foreach ability either with the dolist macro: or the powerful loop macro to iterate on more data types and even with the mapcar function: D{{Main|D (programming language)}}Dart{{Main|Dart (programming language)}}Object Pascal, Delphi{{Main|Object Pascal}}Foreach support was added in Delphi 2005, and uses an enumerator variable that must be declared in the var section. EiffelThe iteration (foreach) form of the Eiffel loop construct is introduced by the keyword In this example, every element of the structure The local entity The iteration form of the Eiffel loop can also be used as a boolean expression when the keyword This iteration is a boolean expression which is true if all items in The following is true if at least one item has a count greater than three: GoGo's foreach loop can be used to loop over an array, slice, string, map, or channel. Using the two-value form, we get the index/key (first element) and the value (second element): Using the one-value form, we get the index/key (first element): [7]GroovyGroovy supports for loops over collections like arrays, lists and ranges: Groovy also supports a C-style for loop with an array index: Collections in Groovy can also be iterated over using the each keyword and a closure. By default, the loop dummy is named it HaskellHaskell allows looping over lists with monadic actions using
It's also possible to generalize those functions to work on applicative functors rather than monads and any data structure that is traversable using Haxe{{Main|Haxe}}JavaIn Java, a foreach-construct was introduced in Java Development Kit (JDK) 1.5.0.[8] Official sources use several names for the construct. It is referred to as the "Enhanced for Loop",[8] the "For-Each Loop",[9] and the "foreach statement".[10] JavaScriptFor unordered iteration over the keys in an Object, JavaScript features the To limit the iteration to the object's own properties, excluding those inherited through the prototype chain, it is sometimes useful to add a hasOwnProperty() test, if supported by the JavaScript engine (for WebKit/Safari, this means "in version 3 or later"). In ECMAScript 5 it is possible to use the keys method of the Object function to iterate over the own keys of an object more naturally. [11]In ECMAScript 5 it's also possible to use the Gecko’s JavaScript engine also has a It is inadvisable to use either a Lua[15]{{Main|Lua (programming language)}}Iterate only through numerical index values: for index, value in ipairs(array) do -- do something end Iterate through all index values:for index, value in pairs(array) do -- do something end Mathematica{{Main|Mathematica}}In Mathematica, It is more common to use MATLAB{{Main|MATLAB}}MintFor each loops are supported in Mint, possessing the following syntax: The in Mint can be written using a for each loop and an infinitely long list.[16] Objective-CForeach loops, called Fast enumeration, are supported starting in Objective-C 2.0. They can be used to iterate over any object that implements the NSFastEnumeration protocol, including NSArray, NSDictionary (iterates over keys), NSSet, etc. NSArrays can also broadcast a message to their members: Where blocks are available, an NSArray can automatically perform a block on every contained item: The type of collection being iterated will dictate the item returned with each iteration. For example: OCamlOCaml is a functional language. Thus, the equivalent of a foreach loop can be achieved as a library function over lists and arrays. For lists: or in short way: For arrays: or in short way: ParaSailThe ParaSail parallel programming language supports several kinds of iterators, including a general "for each" iterator over a container: ParaSail also supports filters on iterators, and the ability to refer to both the key and the value of a map. Here is a forward iteration over the elements of "My_Map" selecting only elements where the keys are in "My_Set": PascalIn Pascal, ISO standard 10206:1990 introduced iteration over set types, thus: PerlIn Perl, foreach (which is equivalent to the shorter for) can be used to traverse elements of a list. The expression which denotes the collection to loop over is evaluated in list-context and each item of the resulting list is, in turn, aliased to the loop variable. List literal example: Array examples: Hash example: Direct modification of collection members: Perl 6In Perl 6, a distinct language from Perl 5, for must be used to traverse elements of a list. (foreach is no longer allowed.) The expression which denotes the collection to loop over is evaluated in list-context, but not flattened by default, and each item of the resulting list is, in turn, aliased to the loop variable(s). List literal example: Array examples: The for loop in its statement modifier form: Hash example: or or Direct modification of collection members with a doubly pointy block, <->: PHP{{Main|PHP}}It is also possible to extract both keys and values using the alternate syntax: Direct modification of collection members:
Python{{Main|Python (programming language)}}Python's tuple assignment, fully available in its foreach loop, also makes it trivial to iterate on (key, value) pairs in associative arrays: As ... though using the Racket{{Main|Racket (programming language)}}or using the conventional Scheme
Ruby{{Main|Ruby (programming language)}}or This can also be used with a hash. Scala{{Main|Scala (programming language)}}Scheme{{Main|Scheme (programming language)}}
Smalltalk{{Main|Smalltalk}}SwiftSwift uses thefor …in construct to iterate over members of a collection.[17]The SystemVerilogSystemVerilog supports iteration over any vector or array type of any dimensionality using the A trivial example iterates over an array of integers:
A more complex example iterates over an associative array of arrays of integers:
TclTcl uses foreach to iterate over lists. It is possible to specify more than one iterator variable, in which case they are assigned sequential values from the list.
It is also possible to iterate over more than one list simultaneously. In the following
Visual Basic .NET{{Main|Visual Basic .NET}}or without type inference WindowsConventional command processor{{main|COMMAND.COM|cmd.exe}}Invoke a hypothetical Windows PowerShell{{Main|Windows PowerShell}}From a pipeline Extensible Stylesheet Language (XSL){{Main|XSL}}[18]See also
References1. ^{{cite web| url=http://www.digitalmars.com/d/statement.html#ForeachStatement| title=D Programming Language foreach Statement Documentation| accessdate=2008-08-04| last=| first=| coauthors=| date=| work=| publisher=Digital Mars}} Цикл просмотра2. ^{{cite web|url=http://blogs.msdn.com/b/vcblog/archive/2011/09/12/10209291.aspx |title=C++11 Features in Visual C++ 11 - Visual C++ Team Blog - Site Home - MSDN Blogs |publisher=Blogs.msdn.com |date=2011-09-12 |accessdate=2013-08-04}} 3. ^{{cite web|url=https://en.cppreference.com/w/cpp/language/range-for |title=Range-based for loop (since C++11) |publisher=en.cppreference.com |date= |accessdate=2018-12-03}} 4. ^{{cite web|url=http://en.cppreference.com/w/cpp/algorithm/for_each |title=std::for_each - cppreference |publisher=en.cppreference.com |date= |accessdate=2017-09-30}} 5. ^{{cite web|url=http://doc.qt.digia.com/4.2/containers.html#the-foreach-keyword |title=Qt 4.2: Generic Containers |publisher=Doc.qt.digia.com |date= |accessdate=2013-08-04}} 6. ^{{cite web|author=Eric Niebler |url=http://www.boost.org/doc/libs/1_53_0/doc/html/foreach.html |title=Chapter 9. Boost.Foreach - 1.53.0 |publisher=Boost.org |date=2013-01-31 |accessdate=2013-08-04}} 7. ^{{cite web | url=http://golang.org/ref/spec#RangeClause | title=Range Clause | publisher=The Go Programming Language | work=The Go Programming Language Specification | accessdate=October 20, 2013}} 8. ^1 "Enhanced for Loop - This new language construct[...]"{{cite web|url=http://java.sun.com/j2se/1.5.0/docs/guide/language/index.html|title=Java Programming Language, Section: Enhancements in JDK 5|accessdate=2009-05-26|year=2004|publisher=Sun Microsystems, Inc.}} 9. ^"The For-Each Loop"{{cite web|url=http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html|title=The For-Each Loop|accessdate=2009-05-10|year=2008|publisher=Sun Microsystems, Inc.}} 10. ^"Implementing this interface allows an object to be the target of the "foreach" statement."{{cite web|url=http://java.sun.com/javase/6/docs/api/java/lang/Iterable.html|title=Iterable (Java Platform SE 6)|accessdate=2009-05-12|year=2004|publisher=Sun Microsystems, Inc.}} 11. ^{{cite web | url= https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys | title=Object.keys | work=Mozilla Developer Network | accessdate=May 7, 2014}} 12. ^{{cite web | url=https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FArray%2FforEach | title=Array.prototype.forEach | work=Mozilla Developer Network | accessdate=October 20, 2013}} 13. ^{{cite web | url=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in | title=JavaScript - for each...in statement | work=Mozilla Developer Network | accessdate=2008-10-03}} 14. ^{{cite web | url=https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in#Description | title=JavaScript - for...in statement on arrays | work=Mozilla Developer Network | accessdate=2008-10-03}} 15. ^{{Cite web|url=https://en.wikibooks.org/wiki/Lua_Programming/Tables#Foreach_loop|title=Lua Programming/Tables - Wikibooks, open books for an open world|website=en.wikibooks.org|language=en|access-date=2017-12-06}} 16. ^{{cite web |url=http://prezi.com/ougvv1wzx2lb/mint-tutorial-part-0/ |title=Mint Tutorial |accessdate=20 October 2013 |author=Chu, Oliver}} 17. ^https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/ControlFlow.html#//apple_ref/doc/uid/TP40014097-CH9-XID_153 18. ^{{cite web | url=https://www.w3schools.com/xsl/xsl_for_each.asp | title=XSLT 11 : Articles with example Ada code|Articles with example Perl code|Articles with example PHP code|Articles with example Python code|Articles with example Racket code|Articles with example Smalltalk code|Articles with example Tcl code|Control flow|Programming language comparisons|Articles with example Java code|Articles with example Haskell code |
||||||||||
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。