LoginSignup
0
1

More than 3 years have passed since last update.

javascript 配列の参照、追加、削除方法 勉強用

Posted at

配列の参照

let firstName = ['kato','sato','suzuki','tanaka','hayama'];

//1番目の要素
console.log('firstName[0]:' + firstName[0]);

//4番目の要素
console.log('firstName[3]:' + firstName[3]);

//6番目の要素(空っぽ)
console.log('firstName[5]:' + firstName[5]);

実行結果

firstName[0]:kato       //firstName[0] katoの要素が取得される。

firstName[3]:tanaka     //firstName[3] tanakaの要素が取得される。

firstName[5]:undefined  //firstName[5] 要素がないのでundefinedが返ってくる。

配列の要素を追加する方法

追加したい配列の現在の一番後ろの要素番号を指定して追加する方法と
pushメソッドを使い要素を追加する方法

let firstName = ['kato','sato','suzuki','tanaka','hayama'];

console.log('追加前:' + firstName);

// 要素を追加
firstName[5] = 'maeda';

console.log('追加後:' + firstName);


// pushメソッドを使い要素を追加
firstName.push('yamada');

console.log('追加:' + firstName);

実行結果

追加前kato,sato,suzuki,tanaka,hayama               //追加前の要素

追加後kato,sato,suzuki,tanaka,hayama,maeda         //指定した要素番号に追加

追加kato,sato,suzuki,tanaka,hayama,maeda,yamada    //一番最後の要素の後ろに追加

配列の要素を削除する方法

let firstName = ['kato','sato','suzuki','tanaka','hayama'];


// ‘sato’君が転校することになった
delete firstName[1];

console.log(firstName);

実行結果

[ 'kato', , 'suzuki', 'tanaka', 'hayama' ]//指定したfirstName[1] satoが削除される。

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