"ForEach"의 두 판 사이의 차이

146번째 줄: 146번째 줄:
# Apple
# Apple
# Mango
# Mango
</source>
<source lang='python'>
fruits = {'a':'apple', 'b':'banana', 'c':'cranberry'}
for key in fruits:
print key + '_' + fruits[key]
# a_apple
# c_cranberry
# b_banana
</source>
</source>



2014년 5월 23일 (금) 17:40 판

extended for
foreach ... as
foreach ... in
each

1 Bash

ARR=("John Smith" "Jane Doe" "Mike Barnes" "Kevin Patterson")
for VALUE in "${ARR[@]}"
do
	echo "[$VALUE]"
done
# [Jonh Smith]
# [Jane Doe]
# [Mike Barnes]
# [Kevin Patterson]

2 C#

// http://msdn.microsoft.com/en-us/library/ttw7t8t6(v=vs.90).aspx
int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in fibarray)
{
  System.Console.WriteLine(i);
}

3 Java

String[] strArr = new String[] { "A", "B", "C", "D" };
for (String str : strArr){
  System.out.println(str);
}

4 JavaScript

  • i is not value but key!
var arr = ["John Smith", "Jane Doe", "Mike Barnes", "Kevin Patterson"];
for(var i in arr) {
  console.log(arr[i]);
}
// John Smith
// Jane Doe
// Mike Barnes
// Kevin Patterson
var arr = ["John Smith", "Jane Doe", "Mike Barnes", "Kevin Patterson"];
for(var i in arr) {
  console.log(i+": "+arr[i]);
}
// 0: John Smith
// 1: Jane Doe
// 2: Mike Barnes
// 3: Kevin Patterson

5 jQuery

var arr = ["John Smith", "Jane Doe", "Mike Barnes", "Kevin Patterson"];
$.each(arr, function() {
  console.log(''+this);
});
// John Smith
// Jane Doe
// Mike Barnes
// Kevin Patterson
var arr = ["John Smith", "Jane Doe", "Mike Barnes", "Kevin Patterson"];
$.each(arr, function(i) {
  console.log(i+': '+this);
});
// 0: John Smith
// 1: Jane Doe
// 2: Mike Barnes
// 3: Kevin Patterson

6 Objective-C

NSArray *strArr = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D"];
for(NSString *str in strArr) {
  NSLog(@"%@\n", str);
}

7 Perl

@strArr = ('A', 'B', 'C', 'D');
foreach $str (@strArr) {
  print "$str ";
}
# A B C D

foreach (@strArr) {
  print "$_ ";
}
# A B C D

for $str (@strArr) {
  print "$str ";
}
# A B C D

for (@strArr) {
  print "$_ ";
}
# A B C D

8 PHP

$strArr = array('A', 'B', 'C', 'D');
foreach ($strArr as $str) {
  echo $str.' ';
}
// A B C D

foreach (range(1,5) as $i) {
  echo "$i ";
}
// 1 2 3 4 5

9 Python

fruits = ['Banana', 'Orange', 'Apple', 'Mango']
for fruit in fruits:
	print fruit
# Banana
# Orange
# Apple
# Mango
fruits = {'a':'apple', 'b':'banana', 'c':'cranberry'}
for key in fruits:
	print key + '_' + fruits[key]
# a_apple
# c_cranberry
# b_banana

10 Ruby

strArr = ['A', 'B', 'C', 'D']
for str in strArr
  puts str
end

strArr.each { |str| puts str }

11 VB

For Each number As Integer In New Long() {45, 3, 987}
  Console.Write(number & " ")
Next
' Output: 45 3 987

12 같이 보기

13 참고 자료