LoginSignup
0
0

More than 1 year has passed since last update.

PHPer脳の人がJavaScriptでループを回す

Last updated at Posted at 2020-02-25

毎回for文書くたびに調べてるので

配列のforeach

phpだとこんな感じのやつ

$array = [1, 2, 3];

foreach($array as $a){
    echo $a;
}

// 1
// 2
// 3

jsだとこう

const array = [1, 2, 3];

for(let a of array){
    console.log(a);
}

// 1
// 2
// 3

連想配列のforeach

phpだとこんな感じのやつ

$array_assoc = [
    1 => 'one',
    2 => 'two',
    3 => 'three'
];

foreach($array_assoc as $k => $v){
    echo $k . ' is ' . $v . "\n";
}

// 1 is one
// 2 is two
// 3 is three

jsだとこう

const array_assoc = {
    1 : 'one',
    2 : 'two',
    3 : 'three'
};

for(let [k, v] of Object.entries(array_assoc)){
    console.log(k + ' is ' + v + "\n");
}

// 1 is one
// 2 is two
// 3 is three

※まあ、jsのObjectは正確には連想配列ではないけど

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0