编程常常会涉及处理冗余任务。for循环有助于缩短代码并减少繁琐的任务。但是对于不同的语言,使用的方法可能不同。这篇文章旨在为Java、Javascript和PHP处理字符串、数组和对象提供一些for循环示例。
循环字符串
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
注意: length()和charAt(index)是String对象类的方法。
JavaScript
var str = "hello";
for (var i=0; i < str.length; i++){
console.log(str.charAt(i));
}
注意: 在JavaScript中,我们可以通过两种方式声明字符串:
var str1 = 'primitive'; //datatype is primitive: string
var str2 = new String('string object'); //string as object
由于基本类型没有方法和属性,因此将str1自动装箱到包装类String(与s2中相同)。 然后str1成为一个String对象,其长度作为属性,其charAt作为其方法,依此类推。
PHP
它不像Java和JavasScript循环字符串那样简单。 一种方法是将字符串转换为数组,然后可以循环该数组。 另一种使用辅助方法的方法substr()来获取字符串的每个字符。
//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;
}
循环数组
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.
注意:数组是具有固定大小的容器对象。创建数组时将确定数组的长度。数组具有length属性,而不是Object中的length方法。实际上,length是Array的公共最终字段。
在此处阅读更多内容。第10章数组(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
}
注意:javascript有另一个for-in循环,通常在Javascript对象循环中使用。
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]) }
}
阅读更多:在JavaScript中循环遍历数组(http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript)
循环对象
Java
在Java中,要循环一个对象数组,可以使用顺序循环或迭代器或for(:)循环##
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
在PHP中,像在数组中一样,使用foreach循环来循环对象。
foreach ($objects as $obj){
echo $obj->property;
}
//or below
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}