0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScript基本まとめ(型)

0
Last updated at Posted at 2024-10-08

つかえる資料にするためにブラッシュアップ中です。いずれTypeScriptへの足掛かりになればと思っています。

データ型の種類

JavaScriptで使用可能なデータ型

データ型 説明
String 文字列 テキストデータを扱う文字列型。
シングルクォート(')、ダブルクォート(")、バッククォート(`)で囲こむ
Number 数値 整数と小数点数の両方を扱える数値型。 
-(253 - 1) ~ 253 - 1 の数値(整数または浮動小数点数)
※ 253 - 1 = 9007199254740991
BigInt 巨大な整数 任意の大きさの整数値
Boolean 真偽値 true/falseの2値のみを持つ論理型。true / false
null ヌル null
意図的に「値がない」ことを表す
undefined 未定義 値が割り当てられていない状態を表す。
undefined
Symbok シンボル ユニークな識別子を作成
Object オブジェクト 複数の値やメソッドをまとめて扱う複合データ型
Array リストデータ 複数の値を順序付きリストとして扱う
Function Function 実行可能なコードブロックを表す

※バッククォートは、「Shiftキーと@の同時押し」

変数に格納される値は、大きく2分類される

分類 説明
プリミティブ型 オブジェクト以外のデータ型 String、null、Number、undefined、BigInt、Symbol、Booleanなど
非プリミティブ型(複合型) オブジェクト Object (Window, Map, Array, Promise, RegExpなど)

JavaScriptの型について

// プリミティブ型(基本型)
number、string、boolean、undefined、null、symbol、bigintなど

  • number
const num = 42;            // 整数
const float = 3.14;        // 浮動小数点
const infinity = Infinity; // 無限大
const notNum = NaN;       // Not a Number
  • string
const str1 = "文字列";
const str2 = 'シングルクォート';
const str3 = `テンプレートリテラル ${num}`;
  • boolean
const isTrue = true;
const isFalse = false;
  • undefined
let undefinedVar;  // 値が未定義
  • null
const nullVar = null;  // 意図的に値が空であることを表す
  • symbol
const sym1 = Symbol('description');
const sym2 = Symbol('description');  // sym1 !== sym2
  • bigint
const bigNum = 9007199254740991n;

オブジェクト型

  • オブジェクトリテラル
const obj = {
    name: "田中",
    age: 25,
    greet() {
        return `こんにちは、${this.name}です`;
    }
};
  • 配列
const arr = [1, 2, 3, "文字列も入れられる", { key: "value" }];
  • 関数
// 関数宣言
function normalFunc(param) {
    return param;
}

// アロー関数
const arrowFunc = (param) => param;
  • Date
const now = new Date();
  • RegExp(正規表現)
const regex = /pattern/g;
// または
const regex2 = new RegExp('pattern', 'g');

特徴

  • 型チェック
// typeofを使用した型チェック
typeof 42;         // "number"
typeof "文字列";   // "string"
typeof true;       // "boolean"
typeof undefined;  // "undefined"
typeof null;       // "object" (これは言語の仕様バグ)
typeof {};         // "object"
typeof [];         // "object"
typeof (() => {}); // "function"
  • instanceof演算子(オブジェクトの型チェック)
    ※オブジェクトが特定のクラス(コンストラクタ関数)のインスタンスかどうかを確認する演算子だそうです。
[] instanceof Array;           // true
new Date() instanceof Date;    // true

// 調べたところあまり使われないような感じだったのですが、また別のブログでまとめたいと思います。
  • プロトタイプチェーン
const arr = [];
// Array → Object → null というプロトタイプチェーンを持つ
console.log(arr.__proto__ === Array.prototype);  // true
console.log(Array.prototype.__proto__ === Object.prototype);  // true

//書いてありましたがこれまたあまり使用されないような感じでした。後日、別のブログで調べてみます。
// プリミティブ型の比較
let a = "文字列";
let b = "文字列";
console.log(a === b);  // true

// オブジェクト型の比較
let obj1 = { value: 42 };
let obj2 = { value: 42 };
console.log(obj1 === obj2);  // false(異なるオブジェクトへの参照)

JavaScriptのキャストについて

  • 文字列への変換
// Stringコンストラクタを使用
String(123)        // "123"
String(true)       // "true"

// toString()メソッドを使用
(123).toString()   // "123"
true.toString()    // "true"

// 文字列結合を利用
123 + ""          // "123"
  • 数値への変換
// Numberコンストラクタを使用
Number("123")     // 123
Number("12.3")    // 12.3
Number("abc")     // NaN

// parseInt/parseFloatを使用
parseInt("123")   // 123
parseFloat("12.3") // 12.3

// 単項演算子+を使用
+"123"            // 123
+"12.3"           // 12.3

//真偽値への変換

// Booleanコンストラクタを使用
Boolean(1)        // true
Boolean(0)        // false
Boolean("")       // false
Boolean("hello")  // true

// 二重否定を使用
!!1               // true
!!0               // false
!!""              // false

暗黙的な型変換を避けるため、明示的な型キャストを使用する。
数値への変換では、parseInt()は整数のみを、parseFloat()は小数点も含めて変換します。
parseInt()を使用する際は、基数を明示的に指定することも出来る。

parseInt("123", 10)  // 10進数として解釈
isNaN(Number("abc"))  // true

リテラル

データ型の値を直接記述するための構文をリテラルと言います。

文字列リテラル

シングルクォート (')、ダブルクォート (")、ES6からはバッククォート ()。 'こんにちは' "こんにちは" こんにちは ${name}さん`

数値リテラル

数値を表す時に使う(0~9)、-もある

BigIntリテラル

数値の後ろに付く n は、BigInt 型のリテラルを表す記号です。
12345678910n

真偽値リテラル

true、false

nullリテラル

null

オブジェクトリテラル

{
name: "名前",
age: 20
}

配列リテラル

[0,1,2,3,4,5,6]

正規表現リテラル

RegExp オブジェクト

関数リテラル

新しい関数の宣言。function を使う。
let function_name = function() {

}

データの確認

データ型の値にtypeofを先頭に付けてコンソールに表示すると、データ型を確認することができます。

console.log(typeof"hello");

string

console.log(typeof 10);

number

console.log(typeof undefined);

undefined

console.log(typeof null);

object

など
※nullはobjectを返すので注意

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?