Help us understand the problem. What is going on with this article?

JavaScriptにおけるfor-in文の動作

JSのfor-in文が思ったように動かない...

素直に配列の中身をfor-in文で取ろうとしたのだが、

sample.js
var a = ["hoge", "fuga", "piyo"];

for (var v in a) {
  console.log(v);
}

/* result
0
1
2
*/

なぜか、0, 1, 2と出る(泣)

JSでは、for-of を使う

sample.js
var a = ["hoge", "fuga", "piyo"];

for (var v of a) {
  console.log(v);
}

/* result
hoge
fuga
piyo
*/

何かと、20分くらい悩んでた...。
PythonやC#などforeach文に慣れているとちょっと違和感w

ちなみに、for-in文の使い方は?

JSでのfor-in文はオブジェクトのプロパティを取得するみたいです。

sample.js
var pen = {
  name: "hoge",
  color: "black",
  price: 100
}

for (var p in pen) {
  console.log(p);
}

/* result
name
color
price
*/
cyan
いろいろ作りたい
https://cyan-0fbcf9.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away