Skip to content

Instantly share code, notes, and snippets.

@ogaty
Last active July 19, 2023 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ogaty/7565b886ee78115a0e1eaa47d6bae68d to your computer and use it in GitHub Desktop.
Save ogaty/7565b886ee78115a0e1eaa47d6bae68d to your computer and use it in GitHub Desktop.
色んな言語のfor foreach

JavaScript

// indexのみ
for (index in a) {
  console.log(a[index]);
}

// 中身のみ
for (i of a) {
  console.log(i);
}
a.forEach((x) => {console.log(x)});

a.forEach((x, index) => {console.log(x)});

Python

for name in arr:
    print(name)
    
for index, name in enumerate(arr):
    print(index)

ruby

for fruit in fruits do  
  p fruit 
end

for key, value in score do
  p key, value
end

strs.each do |str|
  puts str
end

a.each_with_index do |x, i|
  puts "#{i}: #{x}"
end

php

for ($i = 0; $i < 10; $i++) {

}

foreach ($obj as $key => $value) {

}

cSharp

for (int i = 0; i < 10; i++) {
  Debug.WriteLine(i);
}

foreach (Post record in posts) {
  Debug.WriteLine(Post.id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment