型の値(プリミティブ値)
論理型
(Boolean
): 真偽値(true, false)
数値型
(Number
): IEEE 754 の倍精度浮動小数点形式の値
・安全に表現できるのは -(2^(53) − 1)
から 2^(53) − 1
まで
長整数型
(BigInt
): 数値型のように小数を表せないが, 数値型より大きな整数を扱える。
・数値型と値が同じでも, プリミティブ値が異なるので, 厳密等価===
にはならない。
文字列型
(string
): 文字
Null
: 空として定義されている
Undefined
: 定義されていない
シンボル
: 不変のプリミティブ値
変数宣言
-
var
関数内変数 (定義された関数内でしか使用できない) -
let
ブロック{}
内変数 (定義されたブロック{}
内でしか使用できない)
変数再宣言不可
定数宣言
-
const
変数再宣言不可
変数再代入不可
※配列やオブジェクト(辞書)などのmutable
オブジェクトの内容は変更可能
関数宣言
function
function funcName(arg) {
console.log('Hello')
}
arrow function
const arrowFunc = (arg) => {
console.log('Hello')
}
const oneLineArrowFunc = (arg) => console.log('Hello');
引数がない場合は(arg)
を()
に。
for文
for (let i = 0; i < 5; i++) {
console.log()
}
console.log(i);
0
1
2
3
4
4
for (init; condition; afterthought){
statement
}
init
: 一番最初のfor文を実行するための初期設定
condition
: for文が回るたび、最初に評価される。true
であれば続き、false
であればfor文は終わる。
afterthought
: for文の最後に実行される処理
実行される順番はinit
(最初のみ)→ condition
→afterthought
let i = 0; // init
for (;;) {
if (i > 4) break; // condition
console.log(i);
i++; // afterthought
}
console.log(i);
0
1
2
3
4
5
省略する場合, condition
が設定されていないと無限ループするので, 処理の中でbreak
処理を置く。
が, while
の方が明示的
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
0
1
2
3
4
配列メソッド
map()
const array = [2, 4, 6, 8];
const resultArray = array.map(x => x / 2);
console.log(resultArray);
// 出力: Array [1, 2, 3, 4]
x
はarray
の各要素2
, 4
, 6
, 8
をひとつひとつ代入するためのもの
const 変数名 = 配列.map(x => 処理 );
|_________|
引数
filter()
const objectArray = [{id: 'apple', price: 100}, {id: 'suica', price: 200};
const result = objectArray.filter(object => {
return object.id === 'suica'
}
console.log(result) // 出力: [Object {id: 'suica', price: 200}]
const 変数名 = 配列.filter(x => 処理 );
|____________|
引数
return 条件
id
がsuica
のオブジェクトがかえされる。
参考
https://github.com/deatiger/JavaScriptBasic/blob/develop/ArrayMethods/map.js
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/for