From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../reference/global_objects/math/trunc/index.html | 116 +++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.html (limited to 'files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.html') diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.html new file mode 100644 index 0000000000..f260b85c58 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.html @@ -0,0 +1,116 @@ +--- +title: Math.trunc() +slug: Web/JavaScript/Reference/Global_Objects/Math/trunc +tags: + - ECMAScript 2015 + - JavaScript + - Math + - Method +translation_of: Web/JavaScript/Reference/Global_Objects/Math/trunc +--- +
{{JSRef}}
+ +

Math.trunc() 方法会将数字的小数部分去掉,只保留整数部分。

+ +

语法

+ +
Math.trunc(value)
+ +

参数

+ +
+
value
+
任意数字
+
+ +

返回值

+ +

给定数字的整数部分

+ +

描述

+ +

不像 Math 的其他三个方法: {{jsxref("Math.floor()")}}、{{jsxref("Math.ceil()")}}、{{jsxref("Math.round()")}} ,Math.trunc() 的执行逻辑很简单,仅仅是删除掉数字的小数部分和小数点,不管参数是正数还是负数。

+ +

传入该方法的参数会被隐式转换成数字类型。

+ +

因为 trunc()Math 对象的静态方法,你必须用 Math.trunc() 来使用,而不是调用你创建的 Math 对象的一个实例方法(Math 没有构造函数)

+ +

示例

+ +
Math.trunc(13.37)    // 13
+Math.trunc(42.84)    // 42
+Math.trunc(0.123)    //  0
+Math.trunc(-0.123)   // -0
+Math.trunc("-1.123") // -1
+Math.trunc(NaN)      // NaN
+Math.trunc("foo")    // NaN
+Math.trunc()         // NaN
+ +

Polyfill

+ +
if (!Math.trunc) {
+	Math.trunc = function(v) {
+		v = +v;
+		if (!isFinite(v)) return v;
+
+		return (v - v % 1) || (v < 0 ? -0 : v === 0 ? v : 0);
+
+		// 返回:
+		//  0        ->  0
+		// -0        -> -0
+		//  0.2      ->  0
+		// -0.2      -> -0
+		//  0.7      ->  0
+		// -0.7      -> -0
+		//  Infinity ->  Infinity
+		// -Infinity -> -Infinity
+		//  NaN      ->  NaN
+		//  null     ->  0
+	};
+}
+
+ +

或:

+ +
if (!Math.trunc) {
+	Math.trunc = function(v) {
+		v = +v;
+		return (v - v % 1) || (!isFinite(v) || v === 0 ? v : v < 0 ? -0 : 0);
+	};
+}
+ +

规范

+ + + + + + + + + + + + + + + + + + + +
规范名称规范状态备注
{{SpecName('ES2015', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-math.trunc', 'Math.trunc')}}{{Spec2('ESDraft')}} 
+ +

浏览器兼容性

+ +

{{Compat("javascript.builtins.Math.trunc")}}

+ +

相关链接

+ + -- cgit v1.2.3-54-g00ecf