JavaScriptには整数型変数は存在しないため、ある数値の整数部分だけを取り出す。
ある数値の整数部分を取り出すintergerメソッドの実装方法が、JavaScript:the good parts 「良いパーツ」によるベストプラクティス [ ダグラス・クロフォード ] P38に載っている。
Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Number.method('integer', function ( ) {
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
console.log((-10 / 3).integer());// -3
integerメソッドはprototypeを触っているので、これをやめてinteger関数にする場合は次の通りである。
const integer = function(t){
return Math[t < 0 ? 'ceil' : 'floor'](t);
};
console.log(integer(-10 / 3));// -3