GithubHelp home page GithubHelp logo

Comments (16)

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

論理演算子

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

addEventListenerについて

特定のイベントが対象(Element Document Windowなど)で発生した場合に、指定した関数を呼び出す

基本的な構文

// btn要素がクリックされた時に関数funcを呼び出す
btn.addEventListener('click', func);

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

Optional Chainingについて

?.という新しい構文

obj?.fooとした時に、objnullまたはundefinedの場合はundefinedを、そうでないときはobj.fooを返す

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

スプレッド構文について

配列式などの反復可能オブジェクトを展開する

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

importとrequireの違い

  • import
    • ES6の使用
    • 基本的にはフロント側
    • Chromeなどでは動くがIEなどES6に対応していないブラウザでは動かない
  • require
    • CommonJSの仕様
    • サーバー側(nodeで実行するときとか)
    • Nodejs(サーバサイド)では動くがブラウザ側実行のjsでは動かない

メモ

  • importで書くときはbabelを使用する
    • babelを使って内部でrequireに変換する
  • webpackを使い、モジュールバンドルしたりすることでも可能

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

nodemonツール

npm install nodemon

nodemonを使うと自動でサーバーを再起動してくれる、便利ツール
コードの変更時に、自動でプロセスを再起動するので、自分でControl + CとかやらなくてOK

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

package.jsonのdependenciesdevDependenciesの違い

sampleという名前のパッケージを開発しているとする

{ 
  "name": "sample",
  "dependencies": {
    "request": "^2.81.0"
  },
  "devDependencies": {
    "mocha": "^3.4.2"
  }
} 
  • 開発者がpackage.jsonがあるディレクトリでnpm installを使うとdependenciesdevDependenciesどちらもインストールされる
  • パッケージを公開し開発者じゃない人がnpm installすると、dependenciesだけがインストールされる

package.jsonへの追加方法

dependenciesに追加したい時

$npm install --save request

devDependenciesに追加したい時

$npm install --save-dev mocha

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

try catch 構文

try... catch... で例外処理を行う

try {
    //例外エラーが発生するかもしれない処理
} catch( e ) {
    //例外エラーが起きた時に実行する処理
}

例外エラーが発生したときにプログラムを異常終了させないようにする

参照

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

event.tagetについて

入力値の取得は、onChangeイベントの関数にeventという引数を追加し、event.target.valueとすると取得できる

//入力した文字が出力される
<input
  value={this.state.email}
  onChange={(event) => {console.log(event.target.value)}}
/>

メモ:event.preventDefaultについて

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

代入の方法について

返り値の要素を直接代入

//省略形
//右辺の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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

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.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

JavaScriptで連番配列を作る

よく忘れるのでメモ

[...Array(5)].map((_, i) => i) //=> [ 0, 1, 2, 3, 4 ]

参考

from self-study.

Yuya-Furusawa avatar Yuya-Furusawa commented on July 28, 2024

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)
){
  ...
}

参照

from self-study.

Related Issues (11)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.