LoginSignup
1
1

More than 1 year has passed since last update.

【JavaScript】JavaScriptまとめ①

Last updated at Posted at 2023-03-20

概要

JavaScriptの理解を深めるため、
51vlB3JskRL.jpg
で学習した内容を記載していく。1

変数

letによる変数宣言

let 変数名 = 値;

letキーワードに続けて変数名 = 値と書くことで変数を宣言することができる。

文字列

文字列の基本

string_basic.js
const a = 'Hello would';
console.log(a);

「文字列」を記述するには、一連の文字をクォーテーションで囲む。文字列も数値と同じように、変数に格納することができ、console.log()でコンソールに直接表示させることができる。

配列

配列の作り方

[要素1, 要素2, 要素3, ・・・]

要素をカンマ区切りで並べ全体をブラケットで囲む。

create_array.js
const interests = ['読書', '料理', 'キャンプ'];
console.log(interests);

配列の要素にアクセスする

配列[インデックス]

配列に続けて[インデックス]と書くことで、指定したインデックスにアクセスすることができる。

array_element.js
const interests = ['読書', '料理', 'キャンプ',];
const element0 = interests[0]; // インデックス0の要素(先頭の要素)を取得
console.log(element0);

配列の操作

要素の数を調べる

配列に続けて.lengthと書くことで、配列の要素数を得ることができる。

array_length.js
const interests = ['読書', '料理', 'キャンプ'];
const count = interests.length; // 配列の要素数
console.log(count);

要素を最後尾に追加する

配列に続けて.push(追加したい要素)と書くことで、元の配列の一番後ろに要素を追加することができる。

配列.push(追加したい要素)
push.js
const interests = ['読書', '料理', 'キャンプ',];
interests.push('散歩'); // 配列の一番後ろの要素を追加
console.log(interests);

最後尾から要素を取り出す

配列に続けて.pop()と書くことで、配列の最後の要素を取り出すことができる。

配列.pop()
pop.js
const alphabet = ['a', 'b', 'c',];
const last = alphabet.pop(); // 配列の一番後ろに要素を取り出す
console.log(last);

特定の要素が配列に含まれるか調べる

includes()を使うことで、特定の要素が配列に含まれるか調べることができる。

配列.includes(要素)
includes.js
const fruits = ['みかん', 'りんご', 'バナナ',];
const check1 = fruits.includes('りんご'); 
console.log(check1);

配列要素の結合と文字列の分割

join()は、配列の要素を結合して1つの文字列を返してくれる。

配列.join(区切り文字)
join.js
const interests = ['読書', '料理', 'キャンプ',];
const a = interests.join(''); 
console.log(a);

join()とは逆に「文字列」から「配列」を生成するにはsplit()を使う。

文字列.split(区切り文字)
split.js
const string = '読書&料理&キャンプ';
const a = string.split('&'); 
console.log(a);
  1. 本記事では変数、文字列、配列ついて記載した。

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