0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Javascript基礎

0
Last updated at Posted at 2019-10-26
javascript1
<!doctype html>
<html lang="ja">
<head>
 <meta charset="utf-8">
</head>

<div id="id1">新宿</div>
<div id="id2"></div>

<input type="button" onclick="sample(1)" value="実行">

<script>
// alert(1);

// 変数 可変の値の入れ物
const value = '東京';
console.log(value);

// 配列 変数に複数の値を設置できる。前から順に0、1、2・・・とインデックスがつけられる
const items = ['東京', '埼玉', '神奈川'];

// for文。配列をループし展開できる
for (let i = 0; i < items.length; i++) {
  console.log(i, items[i]);
}

// for文の別の書き方 値を取得
for (const item of items) {
  console.log(item);
}

// for文の別の書き方 インデックスを取得
for (const i in items) {
  console.log(i);
}

// if文 
for (const i in items) {
  if (i == 1) {
   console.log('if', items[i]);
  } else if (i == 2){
   console.log('else if', items[i]);
  } else {
   console.log('else', items[i]);
  }
}

// オブジェクト
const obj = {prefectureId: 1, city: [{1: '新宿'}, {2: '池袋'}]};
const prefecture = {1: '東京'};

console.log(obj);

for (const i in obj) {
  // 配列かどうか
  if (Array.isArray(obj[i])) {
    for (const city of obj[i]) {
      // オブジェクトのキーを取得
      const cityId = Object.keys(city);
      console.log(city[cityId]);
    }
  } else {
    console.log(prefecture[obj[i]]);
  }
}

const id1 = document.getElementById('id1').innerHTML;
document.getElementById('id2').innerHTML = id1 + '-池袋';

// 関数。繰り返しでる処理をライブラリにする
function sample (val) {
  alert(val);
}

</script>

</body>
</html>

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?