【js】無名関数と即時関数

無名関数とは

関数名がない
一番のメリットは、関数名を考えなくて良く、メンテナンス性にも貢献
通常の関数とは違って名前がないので、変数に代入するか、別の関数の引数として指定しないとダメ

要は、結局、戻り値がある関数を使うためには結果を変数に代入しないいけなくて
結局変数に入れられる関数に名前っていらなくない?ってなっただけ。
書き方を覚えれば終わり。

書き方

通常

 function sum (price1, price2){
  return price1 + price2;
}

let product_price = sum(2,5);
console.log(product_price);

【結果】
7

無名関数

let funSum = function (price1, price2){
  return price1 + price2;
}

let product_price = funSum(2,5);
console.log(product_price);

【結果】
7


即時関数とは

関数定義した瞬間に、実行される関数のこと
定義した関数の後ろに()という、関数処理するよーの記述をくっつけると、定義→呼び出し、の流れを同時にできる。
また、()内に引数として値や変数なども入れられる。

let funSum = (function (price1, price2){
  return price1 + price2;
})(2,5);

console.log(funSum);

【結果】
7

【js(配列操作)】reduce()

reduce()とは

ループ処理
配列限定
値を合計、または結合する

書き方

map()と同じ。
ただ補足。
変数名.reduce(function(累積値, 要素){ });
・累積値(第一引数)… 配列要素を順番に処理していった値
・要素(第一引数)…… 現在処理中の値

つまり、要素に処理が入り、累積値に格納、これが繰り返され最終形態の累積値が完成!!というロジック

数値の配列がある、合計を出す

  let prices = [200,500,460,759];

  //配列の数値の合計を出す
  let result =  prices.reduce(function(totalVal,price){
    return totalVal + price;
  });
console.log(result);

【結果】
1919


文字の配列がある、結合する

let fruits = ['メロン','バナナ','タンス','ダンス'];

  //配列の数値の合計を出す
  let result = fruits.reduce(function(totalVal,fruit){
    return totalVal + fruit;
  });
console.log(result);

【結果】
メロンバナナタンスダンス

処理を中断できないのでその際は下記参照!!

https://www.sejuku.net/blog/69622www.sejuku.net

【js(配列操作)】filter()

filter()とは

ループ処理
配列限定
条件でソートできる

書き方

map()と同じ。

数値の配列がある、7以下の数値で新たに配列を作る

  let numbers = [1,2,3,4,5,6,7,8,9];

  //7以下を取得して新しい配列にする
  let result = numbers.filter(function(number){
              return number <= 7;
  });
  console.log(result);

【結果】
[1, 2, 3, 4, 5, 6, 7]


文字の配列がある、特定の文字だけ取得する

  let users = ['userID_1234', 'userID_4567', 'userID_8755', 'userID_6876'];

  //文字の配列がある、特定の文字だけ取得する
  let result = users.filter(function(user){
              return user === 'userID_8755';
  });
  console.log(result);

【結果】
["userID_8755"]

外部のオブジェクトと情報を比較して特定の取得する

const MENUS = {
    'グリル' : 750,
    'ポークプレート' : 800,
    'タコライス' : 650,
    'カレー' : 500,
    'カルボナーラ' : 1200,
    'ピザ' : 2400,
    'ビール' : 750,
    'コーラ' : 500,
  };


  let orders = ['ピザ','コーラ','カレー','ポークプレート'];

  //外部のオブジェクトと情報を比較して特定の取得する
  let result = orders.filter(function(order){
              for(let menu in this){
                    if(menu === order){
                      return order;
                    } 
              }
  },MENUS);
  console.log(result);

【結果】
 ["ピザ", "コーラ", "カレー", "ポークプレート"]

参考記事
https://www.sejuku.net/blog/21887www.sejuku.net

【js(配列操作)】map()

map()とは

ループ処理
配列限定
foreachとの違いは”返り値”を返すのでreturnの記述を忘れずに

書き方

配列の変数+.map(コールバック関数);

  <button>処理開始</button>
//ある配列がある
let items = [5,10,15,20,25];

//mapのループ処理の中で各値を2倍にして返している
$('button').click(function(){   
   
  let result = items.map(function(value){
     return value * 2 ;
   });

   console.log(result);

});

【結果】
前: [5, 10, 15, 20, 25]
後:[10, 20, 30, 40, 50]

【解説】
map内の処理を、配列すべての値に対してループ処理で行っている。
必ず、returnは記述すること。

★.map箇所を.foreachにすると、たとえreturnを記述していても、返り値がundefinedになる。
返り値が必要な場合はとにかく「.map」!!


「map」のコールバック関数の応用でさらに便利に…!

value, index, array

「map」のコールバック関数の引数にvalue, index, arrayを入れるとそれぞれ下記。

・「value」は、配列の値
・「index」は、配列のインデックス番号
・「array」は、現在処理している配列

【使いどころ】
index番号を何かしらの条件にする必要がある時。
例)偶数番目の値を2倍にする。

補足:
index番号は0開始なので、仮に配列の先頭を”1つ目”としてカウントする場合は、
index番号が(「配列の値が」ではない)偶数ではない時に値を2倍するという記述になるので注意。

  <button>処理開始</button>
//ある配列がある
let items = [5,10,15,20,25];

//mapのループ処理の中で各値を2倍にして返している
$('button').click(function(){   

  let result = items.map(function( value,index,array ){
      if(index % 2 !== 0){
        return value * 2 ;
      }else{
        return value ;
      }
  });
   console.log(result);

});


【結果】
前:[5, 10, 15, 20, 25]
後:[5, 20, 15, 40, 25]
※見た目上で偶数番目だけ、2倍になっている。

【解説】
map内の処理を、配列すべての値に対してループ処理で行っている。
必ず、returnは記述すること。


ちなみに、「map」は元の配列データに一切変更を加えない特徴がありますが、3つ目の引数「array」を利用すれば、元のデータそのものを変更することも可能です!(グローバル変数のイメージなので関数外でも使える)

//ある配列がある
let items = [5,10,15,20,25];

//mapのループ処理の中で各値を2倍にして返している
$('button').click(function(){   
   
  items.map(function(value,index,array){
    array[index] =  value * 2 ;
   });

   console.log(items);

});

第二引数にオブジェクトを入れる

ループ処理に、別のオブジェクトの情報と関連付けて処理したい。
例)ある生徒たちの出身校を、一覧で表示したい。

【使いどころ】
あるオブジェクトがある。
そのオブジェクトを軸にユーザーのアクションごとに動的にオブジェクトの値を活用したいとき。
※オブジェクトだけでなく、変数などもOK!

<h1>出身校表示</h1>
<button>出身校検索</button>
<div>
    <ul id="show-list">
    </ul>
</div>
//生徒と出身校のオブジェクト
const ROSTER = {
  '田中太郎' : '東京大学',
  '鈴木洋一' : '神奈川大学',
  '澤田和樹' : '明治学院大学',
  '巻楓' : '専修大学',
  'ユリン' : '一橋大学',
  '本田啓介' : '法政大学',
  '長谷部隼' : '関西大学',
  '横山美咲' : '宮崎大学',
};

//ある生徒たちのグループ
let students_groupA = ['鈴木洋一', '澤田和樹', 'ユリン', '横山美咲']; 


//group_A配列の生徒の出身校を出したい
$('button').click(function(){   
    
    //出身校配列の作成
    let groupA_schools = students_groupA.map(function(student){
                            return ROSTER[student];
                        },ROSTER);

    //ループ処理でHTMLで表示
    groupA_schools.forEach(function(school_name){
      //let ID_show_list = document.getElementById('show-list');
      $('#show-list').append('<li>' + school_name + '</li>');
    });


});


【結果】
f:id:aruku-hito:20191219212859p:plain


参考記事
https://www.sejuku.net/blog/21887www.sejuku.net

【jquery】val()

値を取得してくるメソッド。
アクセス文の後につけるだけ。
以下ができる。

・取得
・変更
・追加
・削除

<input id="get" type="text" value="AAA(取得)" placeholder="取得"><br>
<input id="change" type="text" value="BBB(変更)" placeholder="変更"><br>
<input id="new" type="text"  placeholder="追加"><br>
<input id="delete" type="text" value="ZZZ(削除)" placeholder="削除"><br>

<button>要素の取得</button>

実行前
f:id:aruku-hito:20191218213710p:plain

$('button').click(function(){
    let getVal = $('#get').val(); //console.log(getVal); → AAA(取得) を取得できる。
    let changeVal = $('#change').val('FFFF');
    let newVal = $('#new').val('CCCC');
    let deleteval = $('#delete').val('');
});

実行後
f:id:aruku-hito:20191218213837p:plain

【js】getElementsByClassName

概要はgetElementByIdの記事を参照してほしい。

書き方

getElementsByClassName('★★')、★★部分に取得したいHTMLのclassを入力する。

  <!-- 取得 -->
    <p class="sumple">サンプルテキストA</p>
    <p class="sumple">サンプルテキストB</p>
    <p class="sumple test">サンプルテキストC</p>

    <input type="button" id="execute-btn" value="実行">
<script>
$('#execute-btn').click(function(){
    const TEXT = document.getElementsByClassName('sumple');
    console.log(TEXT[0]);
    console.log(TEXT[1]);
});
</script>

結果:取得情報

<p class="sumple">サンプルテキストA</p>
<p class="sumple">サンプルテキストB</p>

【解説】
同じクラス名のHTMLを全て取得してくる。

ここからは例で覚えろ

複数class指定されているHTML要素を取得したいとき

  <!-- 取得 -->
    <p class="sumple">サンプルテキストA</p>
    <p class="sumple">サンプルテキストB</p>
    <p class="sumple test">サンプルテキストC</p>

    <input type="button" id="execute-btn" value="実行">
<script>
$('#execute-btn').click(function(){
    const TEXT = document.getElementsByClassName('test sumple');
    console.log(TEXT[0]);
});
</script>

結果:取得情報

<p class="sumple test">サンプルテキストC</p>


同じようにそのまま複数classを()内に入れればOK。
結果見てわかるようにclassの順番は逆でもOKだが、完全一致のものだけ取得してくる。
(どちらか片方だけのHTMLは無視される)


document部分を変えると対象範囲を狭めれる

document.  → ページ全体が対象
idの範囲指定. → idで囲われたソースコードが対象

そのため、
1. const 定数(変数) = getElementById()で対象範囲のHTMLを取得
2. document.getElementsByClass()の「document.」部分を 1. の要素を代入した変数を入れる
3. const 定数(変数).getElementsByClass()で完成。

 <div id="content-1">    
    <p class="sumple">サンプルテキストA</p>
    <p class="sumple">サンプルテキストB</p>
</div>

<!-- content-2内のsumpleクラスがついたHTMLを取得したい  -->
<div id="content-2">    
  <p class="sumple">This is LemonA</p>
  <p class="sumple">This is LemonB</p>
</div>

<input type="button" id="execute-btn" value="実行">
<script>
$('#execute-btn').click(function(){
  const DIV = document.getElementById('content-2');
  const TEXT = DIV.getElementsByClassName('sumple');
    console.log(TEXT[0]);
    console.log(TEXT[1]);
});
</script>

結果:取得情報

<p class="sumple">This is LemonA</p>
<p class="sumple">This is LemonB</p>

おまけ

2つは似ているがsの有無に注意
getElementById
getElementsByClassName



参考記事
https://www.sejuku.net/blog/68588www.sejuku.net

【js】getElementById

HTML要素を取得

あくまで取得だけである
頻出である。シチュエーションはこうだ。

A子に「告白したい」
A子に「と話したい」
A子に「にプレゼントを渡したい」

A子ちゃんに部分を”アクセス”部分、「」内を”動作部分”とするとgetElementByIdは、”アクセス”部分になる。
そのため、そのあとの動作は+αで記述する必要がある。単体では要素を取得するだけ。

書き方

document.getElementById('★★')、★★部分に取得したいHTMLのidを入力する。

  <!-- 取得 -->
  <div id="content">
    <h1 id="tt-l">12月17日の献立</h1>
    <h2 id="tt-m">野菜炒め定食</h2>
    <p>健康的でおいしかった!特に胡椒が効いていた。</p>
  </div>

  <input type="button" id="change-btn"  value="内容を変更する">
<script>
//アクセスしてHTML要素を取得(→代入)
const TT_l = document.getElementById('tt-l');
console.log(TT_l);

</script>

  <!-- 取得した要素 -->
  <h1 id="tt-l">12月17日の献立</h1>
</script>

取得 + 変更 のお決まりの書き方

冒頭でも述べたが、getElementByIdは、アクセスしてHTML要素を取得するだけだ。
その後、1.その取得した要素を変数に代入 2.それにメソッドをくっつけて料理する

<script>
//1. アクセスしてHTML要素を取得(→代入)
const 変数 = document.getElementById('ID');

//2. メソッドをくっつけて料理
変数.メソッド();
</script>

ここからは例で覚えろ

innerHTML (HTML要素を変更)

  <!-- 取得 -->
  <div id="content">
      <h1 id="tt-l">12月17日の献立</h1>
      <h2 id="tt-m">野菜炒め定食</h2>
      <p>健康的でおいしかった!特に胡椒が効いていた。</p>
  </div>

  <input type="button" id="change-btn"  value="内容を変更する">

f:id:aruku-hito:20191217210133p:plain

クリックすると斜体になりテキストが変更された

<script>
$('#change-btn').click(function(){

    // アクセスしてHTML要素を取得(→代入)
    const TT_l = document.getElementById('tt-l');

   // アクセスした要素が入っている変数にメソッドをつけて要素を変更する
    TT_l.innerHTML = '<i>12月31日の献立</i>';
    console.log(TT_l);

});</script>

f:id:aruku-hito:20191217205236p:plain

※innerHTMLに似てるもので、textContentがあるが以下違う
innerHTML:タグをタグで認識する
textContent:タグを文字列で認識する(タグがそのまま表に表示されるということ)

style (CSSのを変更)

クリックするとデザインが変更された

<script>
$('#change-btn').click(function(){

    //アクセスしてHTML要素を取得(→代入)
    const TT_M = document.getElementById('tt-m');
    
    //アクセスしてCSSを変更
    TT_M.style = 'color:#F0E675; background:#333;font-size:30px;';
});
</script>

f:id:aruku-hito:20191217210903p:plain


+αでフォームなどのvalue属性の値も取得できる

アクセスする末尾に.valueを追加するだけでOK
ユーザーが入れる部分なので変更というよりは、取得して何かの値として使うことや表示することが多い。
以下は、生まれてくる子供の身長を予想するプログラムである
inputで入力された両親の身長のvalueを取得して計算式の値にしている。<式>
男子= (両親の身長の合計+13)/ 2+2
女子= (両親の身長の合計-13)/ 2+2

    <h1 id="tt-l">こどもの予想身長検索</h1>
    <p>数値を入力して計算ボタンをクリックしてください。</p>

    <lavel>こどもの性別</lavel>
    <select id="sex">
      <option value="男の子">男の子</option>
      <option value="女の子">女の子</option>
    </select>
    <p></p>

       <lavel>父親の身長(cm)</lavel>
    <input id="father-height" type="number" value="" placeholder="(例) 170">
    <p></p>
    <lavel>母親の身長(cm)</lavel>
    <input id="mother-height" type="number" value="" placeholder="(例) 155">
    <p></p>
    <input id="execute-btn" type="button" value="計算">

f:id:aruku-hito:20191217220942p:plain

$('#execute-btn').click(function(){
    //プルダウンのvalueを取得
    const SEX = document.getElementById('sex').value;

    //アクセスして身長のinputのvalueで取得
    let father_height = document.getElementById('father-height').value;
    let mother_height = document.getElementById('mother-height').value;

    if( father_height == '' || mother_height == ''){
         alert('もう一度身長をいれてください。');
    }else{
        //文字列→数値
        father_height = Number(father_height);
        mother_height = Number(mother_height);

        //計算
        if(SEX == '男の子'){
          const RESULT = ( father_height + mother_height + 13 ) / 2 + 2;
          alert('将来の生まれる男の子の予想身長は' + RESULT + 'です。');
          document.location.reload()
        }else{
          const RESULT = ( father_height + mother_height - 13 ) / 2 + 2;
          alert('将来の生まれる女の子の予想身長は' + RESULT + 'です。');
          document.location.reload()
        }
  }
});

入力して計算ボタンを押すと将来のこどもの予想身長が表示される
f:id:aruku-hito:20191217221140p:plain