Comments (16)
論理演算子
AND演算子(&&)
左辺がtrueなら右辺を、左辺がfalseなら左辺を返す
a = true
b = false
a && b // => false
b && a // => false
OR演算子(||)
左辺が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
参照
from self-study.
addEventListener
について
特定のイベントが対象(Element
Document
Window
など)で発生した場合に、指定した関数を呼び出す
基本的な構文
// btn要素がクリックされた時に関数funcを呼び出す
btn.addEventListener('click', func);
参照
- EventTarget.addEventListener() - Web API | MDN
- 【JavaScript入門】addEventListener()によるイベント処理の使い方!
- 【Javascript】addEventlistenerについて
from self-study.
Optional Chainingについて
?.
という新しい構文
obj?.foo
とした時に、obj
がnull
またはundefined
の場合はundefined
を、そうでないときはobj.foo
を返す
参照
from self-study.
JavaScriptのテンプレートリテラル
- 忘れがちなのでまとめておく
基本
// これらは全部同じ
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
参照
from self-study.
スプレッド構文について
配列式などの反復可能オブジェクトを展開する
例
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"]
参照
from self-study.
importとrequireの違い
- import
- ES6の使用
- 基本的にはフロント側
- Chromeなどでは動くがIEなどES6に対応していないブラウザでは動かない
- require
- CommonJSの仕様
- サーバー側(nodeで実行するときとか)
- Nodejs(サーバサイド)では動くがブラウザ側実行のjsでは動かない
メモ
- importで書くときはbabelを使用する
- babelを使って内部でrequireに変換する
- webpackを使い、モジュールバンドルしたりすることでも可能
参照
from self-study.
nodemonツール
npm install nodemon
nodemonを使うと自動でサーバーを再起動してくれる、便利ツール
コードの変更時に、自動でプロセスを再起動するので、自分でControl + C
とかやらなくてOK
参照
from self-study.
package.jsonのdependencies
とdevDependencies
の違い
sample
という名前のパッケージを開発しているとする
{
"name": "sample",
"dependencies": {
"request": "^2.81.0"
},
"devDependencies": {
"mocha": "^3.4.2"
}
}
- 開発者がpackage.jsonがあるディレクトリで
npm install
を使うとdependencies
とdevDependencies
どちらもインストールされる - パッケージを公開し開発者じゃない人が
npm install
すると、dependencies
だけがインストールされる
package.jsonへの追加方法
dependencies
に追加したい時
$npm install --save request
devDependencies
に追加したい時
$npm install --save-dev mocha
参照
from self-study.
JavaScriptのオブジェクト
こんな感じでオブジェクトに要素を追加できる
> user_info = {};
> user_info.username = 'mike';
> user_info.email = '[email protected]';
> user_info;
{ username: 'mike', email: '[email protected]' }
こうやって要素を取得できる
> user_info.email;
'[email protected]'
> user_info['email'];
'[email protected]'
こんなのもできる
> 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
参照
from self-study.
try catch 構文
try... catch... で例外処理を行う
try {
//例外エラーが発生するかもしれない処理
} catch( e ) {
//例外エラーが起きた時に実行する処理
}
例外エラーが発生したときにプログラムを異常終了させないようにする
参照
from self-study.
Arrayの操作に関する関数
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) までを取り出す!
参照
from self-study.
event.tagetについて
入力値の取得は、onChange
イベントの関数にevent
という引数を追加し、event.target.value
とすると取得できる
//入力した文字が出力される
<input
value={this.state.email}
onChange={(event) => {console.log(event.target.value)}}
/>
メモ:event.preventDefaultについて
from self-study.
代入の方法について
返り値の要素を直接代入
//省略形
//右辺の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;
returnの省略
{ }を使わない形
//省略した形
const add = (a,b) => a + b;
//省略する前の形
const add = (a,b) => {
return a + b;
}
propsの分割代入
//一番コード量が少ない
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
}
from self-study.
JSのHTML Element操作
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'
});
from self-study.
JavaScriptで連番配列を作る
よく忘れるのでメモ
[...Array(5)].map((_, i) => i) //=> [ 0, 1, 2, 3, 4 ]
参考
from self-study.
Event, Event.target
Event
Event
インターフェイスはDOMで発生するイベントを指す。
Event.target
イベントを発生させたオブジェクトへの参照。
Node
DOMの抽象的な基底クラス。具体的なサブクラスとしてはDocument
, Element
, DocumentFragment
など。
Node.contains()
あるノードが指定されたノードの子孫かどうかを判定する
//otherNodeはNodeオブジェクトでなくてはならない
contains(otherNode);
Reactでoutside clickを実装するときの例
以上より、こんな感じで実装すると安全
if (
ref.current &&
e.target instanceof Node &&
!ref.current.contains(e.target)
){
...
}
参照
- https://developer.mozilla.org/en-US/docs/Web/API/Event
- https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
- https://developer.mozilla.org/en-US/docs/Web/API/Node/contains
from self-study.
Related Issues (11)
- React + TypeScript開発で調べたことのまとめ HOT 28
- 開発の進め方に関する学習 HOT 3
- PATHのお話 HOT 2
- いろいろな概念・用語 HOT 4
- Dockerについて HOT 5
- CSSとか、CSS in JSとか HOT 14
- Node.jsについて HOT 3
- Terraformについて HOT 4
- AWSとか HOT 3
- GitHub Actionsについて
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from self-study.