Programming often involves working on redundant tasks. The for
loops help shorten the code and reduce tedious tasks. But the way for
is used can be different for different languages. This post aims to provide some for
loop examples for Java, Javascript and PHP working on String, Array, and Object.
Loop a String
Java
String str = "hello";
for (int i=0; i < str.length(); i++){
System.out.print(str.charAt(i));
}
//another less optimal solution is to convert the str into an char array
//using str.toCharArray();
//see loop an Array section in Java below
Note:
length() and charAt(index) are methods of String object class.
JavaScript
var str = "hello";
for (var i=0; i < str.length; i++){
console.log(str.charAt(i));
}
Note:
In JavaScript, we can declare string in two ways:
var str1 = 'primitive'; //datatype is primitive: string
var str2 = new String('string object'); //string as object
Since primitive has no methods and property, str1 was autoboxed to wrapper class String (as in s2). Then str1 becomes a String object with length as property and charAt as its method, and so on.
PHP
It is not as simple as Java, and JavasScript looping a string. One way is to convert the string to an array, then we can loop that array. Another way to use helper method, substr() to get each character of the string.
//method 1: use for loop
for($i=0; $i < count($array); $i++){
echo $array[$i];
}
//method 2: convert a string to an array first, then we can loop the array
//use str_split() function to split a string by character
$str = "hello";
$array = str_split($str); //split by character into an array
foreach($array as $value){
echo $value;
}
Loop an Array
Java
int[] nums = new int[5];
for (int i=0; i < nums.length; i++){
nums[i] = i; }
System.out.print(Arrays.toString(nums)); //[0, 1, 2, 3, 4]
//or use for (:) as for each loop
for(int i : nums){
System.out.print(i); //01234
}
//you may compare for(:) loop with foreach loop in PHP and other language.
Note: An array is a container object with a fixed size. The length of an array is established when the array is created. Array has a length property instead of length method in Object. In fact, length is a public final field of Array.
Read more here Chapter 10. Arrays (http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.7)
Javascript
var nums = ["hi", "hello", "you"];
//sequential loop
for (var i=0; i < nums.length; i++){
console.log(num[i])); //hihelloyou
}
Note: javascript has another loop for-in which is commonly used in Javascript object loop.
var obj = { "a": 1, "b": 2, "c": 3};
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
// or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety..
alert("prop: " + prop + " value: " + obj[prop]) }
}
Read more: Loop through array in JavaScript (http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript)
Loop an Object
Java
In Java, to loop an array of objects, we can use sequential loop or iterator or for (:) loop ##
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
Iterator<String> itr = list.iterator();
while(itr.hasNext()){
//do something with itr.next();
//for example itr.remove();
}
//using foreach loop
for( String s : list){
//do something with s
// s is local String variable
//modify s does not modify the list
}
PHP
In PHP, loop an object use foreach loop like in array.
foreach ($objects as $obj){
echo $obj->property;
}
//or below
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}
References
What is the difference between string literals and String objects in JavaScript? (http://stackoverflow.com/questions/17256182/what-is-the-difference-between-string-literals-and-string-objects-in-javascript)
str_split - Manual (http://us.php.net/str_split)
Arrays (The Javaโข Tutorials > Learning the Java Language > Language Basics) (https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
Top comments (29)
Love the apples-to-apples comparison.
Here's Ruby:
But in practice, nobody uses for loops.
Here's a while:
But nobody uses those either.
People are way more likely to do
Or using a collection of objects, like an array or an ActiveRecord collection.
Thank you for adding Ruby syntax. This post was written a few year ago when I found myself always scrambling to write loop when working with different programming languages. Nowadays, a functional programming approach is preferable. I love Python and Ruby for their clean syntax.
Do you mind if I include your Ruby code into the post? I will put credit where it belongs.
Go for it. And no need to credit if it effects the reading in any way. ๐
There's a few other ways to iterate in JavaScript:
for-of
forEach
Functional programming - map
Note:
forEach(console.log)
will print the item, index and the array - developer.mozilla.org/en-US/docs/W...There is no need to use breckets in lambda:
Here's one for Go:
You can also use a while loop:
Note how a "while loop" is basically the same as a for loop.
Or in rust
In Python, this:
or this:
It's why i use Python.
Your PHP string foreach example seems wrong - PHP strings can be referenced like an array. The following works on PHP, for example.
I did include that too, but it was down. Now i moved it to the top. Thanks man.
Let's be fair with Java. The language has seen quite a few enhancements since Java 8 release, 3 years ago, and very recently on Java 9, both on API and syntax. Now using the new stuff...
Loop a string:
Loop a collection:
Nice post! When working with JavaScript/TypeScript, I usually go for the
forEach
array method, which is pretty convenient for usage with functions:If using a library like lodash, you can also iterate over objects (though iteration order is not guaranteed):
Here's the ways to loop a string and an array in C# with a for loop, they're pretty much the same as any other language.
However, C# really likes iterators, so those tasks are most commonly done with a foreach loop.
Then resharper tells you that you can replace that with one line of linq... if my experience is anything to go by ๐
Swift 2, 3, 4:
I never learn/write Swift. Look interesting. Thanks for sharing.