Open Yuya-Furusawa opened 3 years ago
左辺がtrueなら右辺を、左辺がfalseなら左辺を返す
a = true
b = false
a && b // => false
b && a // => false
左辺がtrueなら左辺を、左辺がfalseなら右辺を返す
a = true
b = false
a || b // => true
b || a // => true
明示的にbooleanとして扱う、objectに用いることが多い nullじゃない限りobjectを否定するとfalseになることを利用(nullの場合、否定するとtrueになる)
var hoge = {};
console.log(typeof hoge);//obejct
console.log(hoge);//obejctの中身
console.log(!hoge);//false
console.log(!!hoge);//true
参照
addEventListener
について特定のイベントが対象(Element
Document
Window
など)で発生した場合に、指定した関数を呼び出す
基本的な構文
// btn要素がクリックされた時に関数funcを呼び出す
btn.addEventListener('click', func);
参照
?.
という新しい構文
obj?.foo
とした時に、obj
がnull
またはundefined
の場合はundefined
を、そうでないときはobj.foo
を返す
参照
基本
// これらは全部同じ
var a = 'あいうえお';
var b = "あいうえお ";
var c = `あいうえお`;
// ちなみにシングルクオーテーションとダブルクオーテーションの違いは・・・
var myVar = "I'm fine."; // I'm fine.
var myVar = 'I'm fine.'; // エラー
var myVar = 'I\'m fine.'; // I'm fine.
var myVar = `I'm fine.`; // I'm fine.
var myVar = `I\'m fine.`; // I'm fine.
文字列の中に式を入れられる
// シングルクオーテーション・ダブルクオーテーションではだめ
var d = "あいうえお${1+2}"; //あいうえお${1+2}
// バッククオーテーションをつかう
var e = `あいうえお${1+2}`; //あいうえお3
参照
配列式などの反復可能オブジェクトを展開する
例
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
let lyrics = ['head', parts, 'and', 'toes'];
// ["head", ["shoulders", "knees"], "and", "toes"]
参照
参照
npm install nodemon
nodemonを使うと自動でサーバーを再起動してくれる、便利ツール
コードの変更時に、自動でプロセスを再起動するので、自分でControl + C
とかやらなくてOK
参照
dependencies
とdevDependencies
の違いsample
という名前のパッケージを開発しているとする
{
"name": "sample",
"dependencies": {
"request": "^2.81.0"
},
"devDependencies": {
"mocha": "^3.4.2"
}
}
npm install
を使うとdependencies
とdevDependencies
どちらもインストールされるnpm install
すると、dependencies
だけがインストールされるdependencies
に追加したい時
$npm install --save request
devDependencies
に追加したい時
$npm install --save-dev mocha
参照
こんな感じでオブジェクトに要素を追加できる
> user_info = {};
> user_info.username = 'mike';
> user_info.email = 'mike@gmail.com';
> user_info;
{ username: 'mike', email: 'mike@gmail.com' }
こうやって要素を取得できる
> user_info.email;
'mike@gmail.com'
> user_info['email'];
'mike@gmail.com'
こんなのもできる
> user_info = {name: 'mike'};
> user_info;
{ name: 'mike' }
// 多分1つだけしかコロンで代入できない???
> a = 2;
> user_info = {a, name: 'mike'};
> user_info;
{ a: 2, name: 'mike' }
こういう要素の取り方も
const user = {
id: 42,
is_verified: true
};
const {id, is_verified} = user;
console.log(id); // 42
console.log(is_verified); // true
参照
try... catch... で例外処理を行う
try {
//例外エラーが発生するかもしれない処理
} catch( e ) {
//例外エラーが起きた時に実行する処理
}
例外エラーが発生したときにプログラムを異常終了させないようにする
参照
Array.prototype.filter()
条件にマッチする要素のみを抽出する
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
Array.prototype.unshift()
配列の先頭に1つ以上の要素を追加し、配列の新しい長さを返す
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
// 配列の長さを返す
// expected output: 5
console.log(array1);
// expected output: Array [4, 5, 1, 2, 3]
Array.prototype.splice()
配列の要素を置換したり挿入したりする
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
Array.prototype.slice()
配列の選択した部分を切り取って新しい配列として返す
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
※end がシーケンスの長さを超えた場合も、slice はシーケンスの最後 (arr.length) までを取り出す!
参照
入力値の取得は、onChange
イベントの関数にevent
という引数を追加し、event.target.value
とすると取得できる
//入力した文字が出力される
<input
value={this.state.email}
onChange={(event) => {console.log(event.target.value)}}
/>
//省略形
//右辺のdata要素をstoryIdsとして代入
const { data: storyIds } = await axios.get(
`${BASE_API_URL}/${type}stories.json`
);
//省略する前の形
const response = await axios.get(
`${BASE_API_URL}/${type}stories.json`
);
const storyIds = response.data;
{ }を使わない形
//省略した形
const add = (a,b) => a + b;
//省略する前の形
const add = (a,b) => {
return a + b;
}
//一番コード量が少ない
const Story = ({ story: { id, by, title, kids, time, url } }) => {
// some code
}
//スタンダード
const Story = (props) => {
const { id, by, title, kids, time, url } = props.story;
// some code
}
//propsを使わない形
const Story = ({ story }) => {
const { id, by, title, kids, time, url } = story;
// some code
}
JSで(HTML)Elementを取得し、それを読み取り・操作することができる (例:要素のwidthを取得、要素のスクロール)
Reactであれば、useRef
を使ってHTML Elementを取得することができる
const divElement = useRef<HTMLDivElement>(null);
<div ref={divElement}>
{...}
</div>
他にはgetElementById
とかでも取得できる
const element = document.getElementById('element');
<div id="element">
{...}
</div>
※Element > HTML Elementという感じ。HTML ElementじゃないElementも存在する。SVG Elementとか。
HTMLElement.offsetWidth 要素のレイアウト幅を取得する 参照:https://developer.mozilla.org/ja/docs/Web/API/HTMLElement/offsetWidth
var intElemOffsetWidth = element.offsetWidth;
Element.scrollLeft 左に要素をどれくらいスクロールしたかを取得する(要素を左にスライドさせることができる) 参照:https://developer.mozilla.org/ja/docs/Web/API/Element/scrollLeft
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scrollLeft += 20;
};
Element.scrollBy() 指定された量だけ要素をスクロールする 参照:https://developer.mozilla.org/ja/docs/Web/API/Element/scrollBy
// 上に300、左に300スクロール
// 要素自体を上・左にスクロールするので、要素の下・右側が見えるようになることに注意
element.scrollBy(300, 300);
// optionsの形でもスクロール量を指定可能
element.scrollBy({
top: 100,
left: 100,
behavior: 'smooth'
});
Element.scrollTo()
指定された箇所にスクロール
scrollBy
は「どれくらいスクロールするか」だが、scrollTo
は「どこにスクロールするか」
参照:https://developer.mozilla.org/ja/docs/Web/API/Element/scroll
element.scrollTo({
top: 100,
left: 100,
behavior: 'smooth'
});
よく忘れるのでメモ
[...Array(5)].map((_, i) => i) //=> [ 0, 1, 2, 3, 4 ]
参考
Event
インターフェイスはDOMで発生するイベントを指す。
イベントを発生させたオブジェクトへの参照。
DOMの抽象的な基底クラス。具体的なサブクラスとしてはDocument
, Element
, DocumentFragment
など。
あるノードが指定されたノードの子孫かどうかを判定する
//otherNodeはNodeオブジェクトでなくてはならない
contains(otherNode);
以上より、こんな感じで実装すると安全
if (
ref.current &&
e.target instanceof Node &&
!ref.current.contains(e.target)
){
...
}
参照