いい加減多少まともなJSをかけるようになりたい感じがあるので読んでいる。 知らない文法だけメモ。2章まで読んだ。
Template Strings
let name = "jun"; let msg = `hello $name`;
オブジェクト
オブジェクトと連想配列は、文脈で使い分けられてるが同じものを刺している。 メソッドは関数が格納されたプロパティのことで、あくまでプロパティ。
インクリメント/デクリメント演算子
a = 1; b = 1; a++; // 1 1 ++b; // 2
この時点で変数に格納されてるのはaもbも1。
分割代入
配列
let array = [1,2,3]; let [x,y,z] = array;
x,y,zには1,2,3が代入される。
let array = [1,2,3]; let [x] = array;
xには1が代入される。
let array = [1,2,3]; let [x,...y] = array;
xには1が代入される。 yには[2,3]が代入される。
オブジェクト
let target = {a:1, b:2, c:3}; let {a, b} = target; console.log(a); // 1 console.log(b); // 2
cは無視される。
let target = {a:1, b:2, c:{c2:3}}; let {a, b, c, c:{c2}} = target; console.log(a); // 1 console.log(b); // 2 console.log(c); // {c2:3} console.log(c2); // 3
子要素はこんな感じ。
delete演算子
let array = [1,2,3]; console.log(array); // [1, 2, 3] delete(array[0]); console.log(array); // [empty, 2, 3]
オブジェクトのプロパティも削除できる。参照が消えるが参照先のオブジェクト自体は消えない。
typeof
データ型を表す文字列を返す。配列やオブジェクトは"object"になるのでどのオブジェクトかはわからない。
for...in
let obj = {a:1, b:2} for(let key in obj){ console.log(key + ":" + obj[key]) }
配列の全要素にアクセスするときはlengthを格納したほうがいい
毎回プロパティにアクセスすると性能が劣化する。
for...of
let array = [1,2,3]; for(let val of array){ console.log(val); }
ラベル構文
test: do{ console.log("1") while(true){ console.log("2") break test; } console.log("3") }while(false)
1,2が出力される。 ただのbreakだと1,2,3が出力。
例外
try...catch...finally
try{ let i = 1/j; }catch(e){ console.log(e.message); // j is not defined }finally{ console.log("FINALLY"); }
throw
try{ console.log("try1"); throw new Error("error msg"); console.log("try2"); // 出力されない }catch(e){ console.log(e.message); // error msg }finally{ console.log("FINALLY"); }