LoginSignup
3
0

More than 1 year has passed since last update.

JavaScriptの配列

Last updated at Posted at 2022-03-14

配列とは

配列とは情報をしまっておくためのタンスのようなイメージです。

配列を作る方法

配列を作る方法は下のやり方です。

const array = new.Array();
const array = [];

⚫︎補足
arrayは配列です。

配列の書き方

配列の書き方をみていきます。

const scores = [100, 90, 70]; //数字を入れる
const sportts = ['野球', 'テニス', '柔道']; //文字を入れる
const my_weapon = ['Lightsaber', 2, 'Raygun', 3]; //文字と数字を組み合わせる

あとはconsole.logで出力できます。

次にデータを取る方法です。

const scores = [100, 90, 70];
console.log(scores[0]);

//100と出力

0が1番目から始まるルールがあります。

次にデータを取る方法です。

const scores = [100, 90, 70];
scores.push(60); //pushがデータの追加
console.log(scores);
//[100, 90, 70,60];が出力

次にデータの更新方法です。

const scores = [100, 90, 70];
scores[2] = 80; //更新方法
console.log(scores);

// [100, 90, 80]で出力

こんな感じでできます。

次にデータの削除方法です。削除メソッドはないみたいです。
代わりにspliceを使うみたいです。
配列の要素を操作するメソッドで削除みたいな形式ができるみたいです。

下の資料に詳細があります。
https://techacademy.jp/magazine/37922#sec1

const scores = [100, 90, 70];
scores.splice(2);
console.log(scores);
//100,90が出力

色々組み合わせてできるみたいです。

スプレッド演算子

これは...〜みたいな形で配列の文字列展開できるみたいです。

⚫︎最大値 最小値
これもスプレッド演算子で出せます。maxとminは最大値と最小値です。

const scores = [100, 70, 90];
console.log(Math.max(...scores));
//100  最大値

const scores = [100, 70, 90];
console.log(Math.min(...scores));
// 70 最小値

⚫︎配列の結合
スプレッド演算子で配列を結合できます。

const scoreA = [10, 30, 40];
const scoreB = [100, 400, 500];

const numberC = [...scoreA, ...scoreB]; //スプレッド演算子
console.log(numberC);

//[10, 30, 40, 100, 400, 500]で出力

const numberC = [...scoreA, ...scoreB];に注目してもらえればわかるのですが
この形で結合することができます。

⚫︎オブジェクトのやり方
オブジェクトの使い方は下の資料に記載があります。今回は配列の記事なのでオブジェクトは割愛します。

いろいろな配列のメソッド

配列はいろいろなメソッドがありカンファレンスやドキュメントを確認して調べながらできます。
やりたいことを言葉にできれば調べることができたりします。

⚫︎配列の中身の確認
includes

⚫︎配列公式ドキュメント
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array

⚫︎参考資料
https://qiita.com/takeshisakuma/items/b23b1a748098f30e2ff2
https://blog.codecamp.jp/javascript-array-use
https://qiita.com/akisx/items/682a4283c13fe336c547

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