数字和日期

This chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in JavaScript. This includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global Math object to perform a wide variety of mathematical operations on numbers.

数字

In JavaScript, numbers are implemented in double-precision 64-bit binary format IEEE 754 (i.e., a number between ±2 −1022 and ±2 +1023 , or about ±10 −308 to ±10 +308 , with a numeric precision of 53 bits). Integer values up to ±2 53 − 1 can be represented exactly.

In addition to being able to represent floating-point numbers, the number type has three symbolic values: + Infinity , - Infinity ,和 NaN (not-a-number).

A more recent addition to JavaScript is BigInt which lets you represent integers that may be very large. There are caveats to using BigInt , however; for example, you can't mix and match BigInt and Number values in the same operation, and you can't use the Math object with BigInt values.

另请参阅 JavaScript data types and structures for context with other primitive types in JavaScript.

You can use four types of number literals: decimal, binary, octal, and hexadecimal.

Decimal numbers

1234567890
42
// Caution when using leading zeros:
0888 // 888 parsed as decimal
0777 // parsed as octal in non-strict mode (511 in decimal)
				

Note that decimal literals can start with a zero ( 0 ) followed by another decimal digit, but if every digit after the leading 0 is smaller than 8, the number gets parsed as an octal number.

Binary numbers

Binary number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "B" ( 0b or 0B ). If the digits after the 0b are not 0 or 1, the following SyntaxError is thrown: "Missing binary digits after 0b".

var FLT_SIGNBIT  = 0b10000000000000000000000000000000; // 2147483648
var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040
var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
				

Octal numbers

Octal number syntax uses a leading zero. If the digits after the 0 are outside the range 0 through 7, the number will be interpreted as a decimal number.

var n = 0755; // 493
var m = 0644; // 420
				

Strict mode in ECMAScript 5 forbids octal syntax. Octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%" . In ECMAScript 2015, octal numbers are supported if they are prefixed with 0o , e.g.:

var a = 0o10; // ES2015: 8
				

Hexadecimal numbers

Hexadecimal number syntax uses a leading zero followed by a lowercase or uppercase Latin letter "X" ( 0x or 0X) . If the digits after 0x are outside the range (0123456789ABCDEF),  the following SyntaxError is thrown: "Identifier starts immediately after numeric literal".

0xFFFFFFFFFFFFFFFFF // 295147905179352830000
0x123456789ABCDEF   // 81985529216486900
0XA                 // 10
				

Exponentiation

1E3   // 1000
2e6   // 2000000
0.1e2 // 10
				

Number object

The built-in Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:

var biggestNum = Number.MAX_VALUE;
var smallestNum = Number.MIN_VALUE;
var infiniteNum = Number.POSITIVE_INFINITY;
var negInfiniteNum = Number.NEGATIVE_INFINITY;
var notANum = Number.NaN;
				

You always refer to a property of the predefined Number object as shown above, and not as a property of a Number object you create yourself.

The following table summarizes the Number object's properties.

Properties of Number
Property 描述
Number.MAX_VALUE The largest representable number ( ±1.7976931348623157e+308 )
Number.MIN_VALUE The smallest representable number ( ±5e-324 )
Number.NaN Special "not a number" value
Number.NEGATIVE_INFINITY Special negative infinite value; returned on overflow
Number.POSITIVE_INFINITY Special positive infinite value; returned on overflow
Number.EPSILON Difference between 1 and the smallest value greater than 1 that can be represented as a Number ( 2.220446049250313e-16 )
Number.MIN_SAFE_INTEGER Minimum safe integer in JavaScript (−2 53 + 1, or −9007199254740991 )
Number.MAX_SAFE_INTEGER Maximum safe integer in JavaScript (+2 53 − 1, or +9007199254740991 )
Methods of Number
Method 描述
Number.parseFloat() Parses a string argument and returns a floating point number.
Same as the global parseFloat() 函数。
Number.parseInt() Parses a string argument and returns an integer of the specified radix or base.
Same as the global parseInt() 函数。
Number.isFinite() Determines whether the passed value is a finite number.
Number.isInteger() Determines whether the passed value is an integer.
Number.isNaN() Determines whether the passed value is NaN . More robust version of the original global isNaN() .
Number.isSafeInteger() Determines whether the provided value is a number that is a safe integer .

Number prototype provides methods for retrieving information from Number objects in various formats. The following table summarizes the methods of Number.prototype .

Methods of Number.prototype
Method 描述
toExponential() Returns a string representing the number in exponential notation.
toFixed() Returns a string representing the number in fixed-point notation.
toPrecision() Returns a string representing the number to a specified precision in fixed-point notation.

Math object

The built-in Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as

Math.PI
				

Similarly, standard mathematical functions are methods of Math . These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write

Math.sin(1.56)
				

Note that all trigonometric methods of Math take arguments in radians.

The following table summarizes the Math object's methods.

Methods of Math
Method 描述
abs() Absolute value
sin() , cos() , tan() Standard trigonometric functions; with the argument in radians.
asin() , acos() , atan() , atan2() Inverse trigonometric functions; return values in radians.
sinh() , cosh() , tanh() Hyperbolic functions; argument in hyperbolic angle.
asinh() , acosh() , atanh() Inverse hyperbolic functions; return values in hyperbolic angle.

pow() , exp() , expm1() , log10() , log1p() , log2()

Exponential and logarithmic functions.
floor() , ceil() Returns the largest/smallest integer less/greater than or equal to an argument.
min() , max() Returns the minimum or maximum (respectively) value of a comma separated list of numbers as arguments.
random() Returns a random number between 0 and 1.
round() , fround() , trunc() , Rounding and truncation functions.
sqrt() , cbrt() , hypot() Square root, cube root, Square root of the sum of square arguments.
sign() The sign of a number, indicating whether the number is positive, negative or zero.
clz32() ,
imul()
Number of leading zero bits in the 32-bit binary representation.
The result of the C-like 32-bit multiplication of the two arguments.

Unlike many other objects, you never create a Math object of your own. You always use the built-in Math 对象。

Date object

JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00, with a Unix Timestamp being the number of seconds since January 1, 1970, 00:00:00.

Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

To create a Date 对象:

var dateObjectName = new Date([parameters]);
				

where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

调用 Date without the new keyword returns a string representing the current date and time.

parameters in the preceding syntax can be any of the following:

Methods of the Date object

Date object methods for handling dates and times fall into these broad categories:

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

For example, suppose you define the following date:

var Xmas95 = new Date('December 25, 1995');
				

Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 1995.

getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date 对象。

For example, the following code displays the number of days left in the current year:

var today = new Date();
var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month
endYear.setFullYear(today.getFullYear()); // Set year to this year
var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day
var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;
var daysLeft = Math.round(daysLeft); //returns days left in the year
				

This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today and endYear ,使用 getTime and rounding to a whole number of days.

parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate 对象:

var IPOdate = new Date();
IPOdate.setTime(Date.parse('Aug 9, 1995'));
				

范例

In the following example, the function JSClock() returns the time in the format of a digital clock.

function JSClock() {
  var time = new Date();
  var hour = time.getHours();
  var minute = time.getMinutes();
  var second = time.getSeconds();
  var temp = '' + ((hour > 12) ? hour - 12 : hour);
  if (hour == 0)
    temp = '12';
  temp += ((minute < 10) ? ':0' : ':') + minute;
  temp += ((second < 10) ? ':0' : ':') + second;
  temp += (hour >= 12) ? ' P.M.' : ' A.M.';
  return temp;
}
				

JSClock function first creates a new Date object called time ; since no arguments are given, time is created with the current date and time. Then calls to the getHours , getMinutes ,和 getSeconds methods assign the value of the current hour, minute, and second to hour , minute ,和 second .

The next four statements build a string value based on the time. The first statement creates a variable temp , assigning it a value using a conditional expression; if hour is greater than 12, ( hour - 12 ), otherwise simply hour, unless hour is 0, in which case it becomes 12.

The next statement appends a minute value to temp . If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp in the same way.

Finally, a conditional expression appends "P.M." to temp if hour is 12 or greater; otherwise, it appends "A.M." to temp .

  1. JavaScript
  2. 教程:
  3. 完整初学者
    1. JavaScript 基础
    2. JavaScript 第一步
    3. JavaScript 构建块
    4. 引入 JavaScript 对象
  4. JavaScript 指南
    1. 介绍
    2. 语法和类型
    3. 控制流程和错误处理
    4. 循环和迭代
    5. 函数
    6. 表达式和运算符
    7. 数字和日期
    8. 文本格式
    9. 正则表达式
    10. Indexed collections
    11. Keyed collections
    12. Working with objects
    13. 对象模型的细节
    14. Using promises
    15. 迭代器和生成器
    16. Meta programming
    17. JavaScript 模块
  5. 中间体
    1. 引入 JavaScript 对象
    2. 客户端侧 Web API
    3. 重新介绍 JavaScript
    4. JavaScript 数据结构
    5. 相等比较和相同
    6. 闭包
  6. 高级
    1. 继承和原型链
    2. 严格模式
    3. JavaScript 类型数组
    4. 内存管理
    5. 并发模型和事件循环
  7. 参考:
  8. 内置对象
    1. AggregateError
    2. Array
    3. ArrayBuffer
    4. AsyncFunction
    5. Atomics
    6. BigInt
    7. BigInt64Array
    8. BigUint64Array
    9. Boolean
    10. DataView
    11. Date
    12. Error
    13. EvalError
    14. Float32Array
    15. Float64Array
    16. Function
    17. Generator
    18. GeneratorFunction
    19. Infinity
    20. Int16Array
    21. Int32Array
    22. Int8Array
    23. InternalError
    24. Intl
    25. JSON
    26. Map
    27. Math
    28. NaN
    29. Number
    30. Object
    31. Promise
    32. Proxy
    33. RangeError
    34. ReferenceError
    35. Reflect
    36. RegExp
    37. Set
    38. SharedArrayBuffer
    39. String
    40. Symbol
    41. SyntaxError
    42. TypeError
    43. TypedArray
    44. URIError
    45. Uint16Array
    46. Uint32Array
    47. Uint8Array
    48. Uint8ClampedArray
    49. WeakMap
    50. WeakSet
    51. WebAssembly
    52. decodeURI()
    53. decodeURIComponent()
    54. encodeURI()
    55. encodeURIComponent()
    56. escape()
    57. eval()
    58. globalThis
    59. isFinite()
    60. isNaN()
    61. null
    62. parseFloat()
    63. parseInt()
    64. undefined
    65. unescape()
    66. uneval()
  9. 表达式 & 运算符
    1. 算术运算符
    2. 赋值运算符
    3. Bitwise operators
    4. 逗号运算符
    5. Comparison operators
    6. 条件 (三元) 运算符
    7. Destructuring assignment
    8. Function expression
    9. Grouping operator
    10. Logical operators
    11. Nullish coalescing operator
    12. Object initializer
    13. 运算符优先级
    14. Optional chaining
    15. Pipeline operator
    16. 特性访问器
    17. 传播句法
    18. 异步函数表达式
    19. await
    20. class expression
    21. delete operator
    22. function* 表达式
    23. in operator
    24. instanceof
    25. new operator
    26. new.target
    27. super
    28. this
    29. typeof
    30. void 运算符
    31. yield
    32. yield*
  10. 语句 & 声明
    1. async function
    2. block
    3. break
    4. class
    5. const
    6. continue
    7. debugger
    8. default
    9. do...while
    10. empty
    11. export
    12. for
    13. for await...of
    14. for...in
    15. for...of
    16. 函数声明
    17. function*
    18. if...else
    19. import
    20. import.meta
    21. label
    22. let
    23. return
    24. switch
    25. throw
    26. try...catch
    27. var
    28. while
    29. with
  11. 函数
    1. 箭头函数表达式
    2. 默认参数
    3. 方法定义
    4. 其余参数
    5. 自变量对象
    6. getter
    7. setter
    1. Class fields
    2. 构造函数
    3. extends
    4. static
  12. 错误
    1. Error: Permission denied to access property "x"
    2. InternalError: too much recursion
    3. RangeError: argument is not a valid code point
    4. RangeError: invalid array length
    5. RangeError: invalid date
    6. RangeError: precision is out of range
    7. RangeError: radix must be an integer
    8. RangeError: repeat count must be less than infinity
    9. RangeError: repeat count must be non-negative
    10. ReferenceError: "x" is not defined
    11. ReferenceError: assignment to undeclared variable "x"
    12. ReferenceError: can't access lexical declaration`X' before initialization
    13. ReferenceError: deprecated caller or arguments usage
    14. ReferenceError: invalid assignment left-hand side
    15. ReferenceError: reference to undefined property "x"
    16. SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
    17. SyntaxError: "use strict" not allowed in function with non-simple parameters
    18. SyntaxError: "x" is a reserved identifier
    19. SyntaxError: JSON.parse: bad parsing
    20. SyntaxError: Malformed formal parameter
    21. SyntaxError: Unexpected token
    22. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
    23. SyntaxError: a declaration in the head of a for-of loop can't have an initializer
    24. SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
    25. SyntaxError: for-in loop head declarations may not have initializers
    26. SyntaxError: function statement requires a name
    27. SyntaxError: identifier starts immediately after numeric literal
    28. SyntaxError: illegal character
    29. SyntaxError: invalid regular expression flag "x"
    30. SyntaxError: missing ) after argument list
    31. SyntaxError: missing ) after condition
    32. SyntaxError: missing : after property id
    33. SyntaxError: missing ; before statement
    34. SyntaxError: missing = in const declaration
    35. SyntaxError: missing ] after element list
    36. SyntaxError: missing formal parameter
    37. SyntaxError: missing name after . operator
    38. SyntaxError: missing variable name
    39. SyntaxError: missing } after function body
    40. SyntaxError: missing } after property list
    41. SyntaxError: redeclaration of formal parameter "x"
    42. SyntaxError: return not in function
    43. SyntaxError: test for equality (==) mistyped as assignment (=)?
    44. SyntaxError: unterminated string literal
    45. TypeError: "x" has no properties
    46. TypeError: "x" is (not) "y"
    47. TypeError: "x" is not a constructor
    48. TypeError: "x" is not a function
    49. TypeError: "x" is not a non-null object
    50. TypeError: "x" is read-only
    51. TypeError: 'x' is not iterable
    52. TypeError: More arguments needed
    53. TypeError: Reduce of empty array with no initial value
    54. TypeError: X.prototype.y called on incompatible type
    55. TypeError: can't access dead object
    56. TypeError: can't access property "x" of "y"
    57. TypeError: can't assign to property "x" on "y": not an object
    58. TypeError: can't define property "x": "obj" is not extensible
    59. TypeError: can't delete non-configurable array element
    60. TypeError: can't redefine non-configurable property "x"
    61. TypeError: cannot use 'in' operator to search for 'x' in 'y'
    62. TypeError: cyclic object value
    63. TypeError: invalid 'instanceof' operand 'x'
    64. TypeError: invalid Array.prototype.sort argument
    65. TypeError: invalid arguments
    66. TypeError: invalid assignment to const "x"
    67. TypeError: property "x" is non-configurable and can't be deleted
    68. TypeError: setting getter-only property "x"
    69. TypeError: variable "x" redeclares argument
    70. URIError: malformed URI sequence
    71. Warning: -file- is being assigned a //# sourceMappingURL, but already has one
    72. Warning: 08/09 is not a legal ECMA-262 octal constant
    73. Warning: Date.prototype.toLocaleFormat is deprecated
    74. Warning: JavaScript 1.6's for-each-in loops are deprecated
    75. Warning: String.x is deprecated; use String.prototype.x instead
    76. Warning: expression closures are deprecated
    77. Warning: unreachable code after return statement
  13. 杂项
    1. JavaScript technologies overview
    2. 词汇语法
    3. JavaScript 数据结构
    4. Enumerability and ownership of properties
    5. Iteration protocols
    6. 严格模式
    7. Transitioning to strict mode
    8. Template literals
    9. 弃用特征