アロー関数と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]
というブロック構文。
- 式とはある値へと決定される有効なコード単位のこと
- 副作用のある式と副作用がない式
式の種類
- 算術式
- 文字列式
- 論理式
- 基本式
- 左辺式
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
ややこしい。演算子によって明示された文字列を数値として取り扱ったり、明示された数値を文字列と扱ったりするからややこしい。 でも自分で変数の型を意識すれば多分大丈夫。
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演算子は引数の型を返す演算子。()はあってもなくてもいい?
[1,2,3] instanceof Array // true
"yamada" instanceof Array // false
parseFloat()``parseInt()
はNumberオブジェクトのメソッド。
Number.parseInt("3.14") // 3
Number.parseFloat("3.14") // 3.14
Math.PI // 3.141592653589793
三角函数、対数函数、指数函数や各種丸め函数などが使える。
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
パラメータ無しで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