javascript sliceを使用して配列の最後の値を取得する

javascript sliceを使用して配列の最後の値を取得する

javascriptで、sliceを使用して配列の最後の値を取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

sliceを使用して配列の最後の値を取得

「slice」は、マイナスを指定すると最後から取得することができるので、これを利用して配列の最後の値を取得することが可能です。

const arr = [
  "aaa",
  "bbb",
  "ccc"
]

console.log(
  arr.slice(-1)[0] // ccc
)

console.log(
  arr // ['aaa', 'bbb', 'ccc'] 元の値は変わりません
)

実行結果を確認すると、配列の最後のコードが取得されていることが確認できます。

「arr.slice(-1)」は、以下の値を取得するので、この取得した配列の最初のインデックス「0」を指定することで、最後の値を取得してます。

console.log(
  arr.slice(-1) // ["ccc"]
)

ちなみに「slice()」は、配列内にオブジェクトや配列がない場合は、コピー元の値を変更してもコピー先が変わらいないようすることができます。

const arr = ["aaa", "bbb", "ccc"]

const newArr1 = arr;
const newArr2 = arr.slice();

console.log( arr.slice(-1)[0] ); // ccc
console.log( newArr1.slice(-1)[0] ); // ccc
console.log( newArr2.slice(-1)[0] ); // ccc

arr[3] = 'ddd';

console.log( arr.slice(-1)[0] ); // ddd
console.log( newArr1.slice(-1)[0] ); // ddd
console.log( newArr2.slice(-1)[0] ); // ccc

サンプルコード

以下は、
「実行」ボタンをクリックして、ランダムな配列を生成して、sliceで最後の値を取得して表示するサンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">  
</head>

<script>

  const hoge = () => {
    
    // ランダムな配列を3個生成
    const arr = Array(3).fill().map(x => ~~(Math.random() * 10));

    disp(arr, "foo");

    fuga.innerHTML = arr.slice(-1)[0];

  }

  //フロントに表示する関数
  const disp = (arr, id) => {

    let text = [];

    arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'));

    document.getElementById(id).innerHTML = text.join('');

  }

  window.onload = () => {

    btn.onclick = () => { hoge() };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">
      
      <h1 class="font-semibold text-red-500 text-lg mr-auto">元の配列</h1>
      <ul id="foo" class="font-semibold text-lg mr-auto"></ul>      
      
      <h1 class="font-semibold text-red-500 text-lg mr-auto">実行結果</h1>
      <h1 id="fuga" class="font-semibold text-lg mr-auto"></h1>

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-red-500 text-red-700 font-semibold hover:text-white py-2 px-4 border border-red-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

実行結果を確認すると、最後の値が取得されていることが確認できます。