Skip to content

Instantly share code, notes, and snippets.

@YuukiToriyama
Last active September 28, 2019 16:39
Show Gist options
  • Save YuukiToriyama/76aa78b7aa61bdb9952f4f13949d9827 to your computer and use it in GitHub Desktop.
Save YuukiToriyama/76aa78b7aa61bdb9952f4f13949d9827 to your computer and use it in GitHub Desktop.
備忘録

函数

アロー関数(=>)

アロー関数とfunction(){}構文は同じ。アロー(=>)を使って書いたほうが直感的かな?

[1,2,3,4].map(function(x) {return x * x}) // [1,4,9,16]
[1,2,3,4].map(x => x * x)                 // [1,4,9,16]

Rubyだと、

[1,2,3,4].map{|x| x * x} # [1,4,9,16]

というブロック構文。

式と演算子

式(expression)

  • 式とはある値へと決定される有効なコード単位のこと
  • 副作用のある式と副作用がない式

式の種類

  • 算術式
  • 文字列式
  • 論理式
  • 基本式
  • 左辺式

演算子(operator)

短絡評価(short-circuit evaluation?)

  • false && anythingはanythingの如何に関わらず、即座にfalseと評価される。
  • true || anythingはanythingの如何に関わらず、即座にtrueと評価される。

たとえば

console.log(true || unko) // unkoなんて変数は宣言してない

と打ってもエラーは出ず、trueと表示される。どうやらanything部分は一切評価されていないようだ。

文字列演算子の+と四則演算の+

"1234" + "5" // '12345'
"1234" + 5   // '12345'
"1234" - 5   // 1229
"1234" - "5" // 1229

ややこしい。演算子によって明示された文字列を数値として取り扱ったり、明示された数値を文字列と扱ったりするからややこしい。 でも自分で変数の型を意識すれば多分大丈夫。

単項演算子 typeof

RubyでいうところのObject#classみたいなものかな?ちょっと違うか。

var func = function(x) {return x**2 + x + 1}
func(3) // 13

console.log(typeof(func))    // 'function'
console.log(typeof(func(3))) // 'number'

typeof演算子は引数の型を返す演算子。()はあってもなくてもいい?

関係演算子 instanceof

[1,2,3] instanceof Array  // true
"yamada" instanceof Array // false

Numberオブジェクトメソッド

parseFloat()``parseInt()はNumberオブジェクトのメソッド。

Number.parseInt("3.14")   // 3
Number.parseFloat("3.14") // 3.14

Mathオブジェクト

PIプロパティ

Math.PI // 3.141592653589793

Mathオブジェクトメソッド

三角函数、対数函数、指数函数や各種丸め函数などが使える。

const pi = Math.PI
Math.sin(pi/2) // 1
Math.cos(pi)   // -1
Math.tan(pi/4) // 0.9999999999999999

Math.asin(1) * 2 // 3.141592653589793
Math.acos(0) * 2 // 3.141592653589793
Math.atan(1) * 4 // 3.141592653589793
Math.pow(5,3) // 125

Math.exp(1)       // 2.718281828459045
Math.log2(1024)   // 10
Math.log10(10000) // 4
const pi = Math.PI

Math.floor(pi) // 3
Math.ceil(pi)  // 4
Math.abs(-3)  // 3
Math.abs(3)   // 3
Math.sign(-3) // -1
Math.sign(3)  // 1

Math.sqrt(3) // 1.7320508075688772
Math.cbrt(3) // 1.4422495703074083

Math.hypot(3,4)  // 5
Math.hypot(12,5) // 13

Dateオブジェクト

パラメータ無しでnew Dateとすると、今の日時を表すDateオブジェクトが作成される。

new Date                      // 2019-09-28T16:13:18.698Z
new Date("1989-09-10 12:32")  // 1989-09-10T03:32:00.000Z

var d = new Date
console.log(d instanceof Date) // true

文字列

Stringオブジェクト

テキスト処理 - JavaScript | MDN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment