This section describes how to master the numbers and date types in JavaScript
DigitalEDIT
In JavaScript, numbers are double-precision floating-point types double-precision 64-bit binary format IEEE 754 (that is, A number can only be between-(253-1) and 253-1). there is no specific data type for integer type. In addition to being able to represent floating-point numbers, the number type has three symbol values: +
Infinity
, -
Infinity
and NaN
(not-a-number). See JavaScript data types and structures in the JavaScript guide to learn more about other basic types.
You can use four types of digital binary: decimal, binary, octal, and Hexadecimal.
Decimal digits (decimal Numbers)
123456789042// 数字第一个为零的注意事项:0888 // 888 将被当做十进制处理0777 // 在非严格格式下会被当做八进制处理 (用十进制表示就是511)
Note that decimal can begin with 0, followed by other decimal digits, but if the subsequent decimal number is less than 8, then the number will be treated as Octal.
Binary digits (binary Numbers)
The binary numeric syntax is preceded by a zero, followed by a lowercase or uppercase Latin letter B ( 0b或者是0B
). If the number after 0b is not 0 or 1, then the syntax error ( SyntaxError):
"Missing binary digits after 0b") is Indicated.
var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607
Octal digits (octal Numbers)
The octal numeric syntax begins with 0. If the number after 0 is not within the range of 0 to 7, the number will be converted to a decimal number.
var n = 0755; // 493var m = 0644; // 420
Hex (hexadecimal Numbers)
The hexadecimal number syntax begins with a zero, followed by a lowercase or uppercase Latin letter x ( 0x或者是0X
). If 0x
the following numbers exceed the specified range (0123456789ABCDEF), then this syntax error is prompted ( SyntaxError):
"Identifier starts immediately after numeric literal".
0xFFFFFFFFFFFFFFFFF // 2951479051793528300000x123456789ABCDEF // 819855292164869000XA // 10
Exponential form (exponentiation)
1E3 // 10002e6 // 20000000.1e2 // 10
Numeric ObjectsEDIT
Built-in Number
objects have some digitized constant properties, such as maximum, not a number, and Infinity. You cannot change the values of these properties, but you can 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 will always use only the properties that are displayed from the Number object reference, not the property of the number object that you created Yourself.
The following table summarizes the properties of a numeric object:
The properties of a number
properties |
description |
number.max_value |
The maximum value that can be represented |
number.min_value |
can represent the smallest Value |
Number.NaN |
specifically "non-numeric" |
number.negative_ INFINITY |
specifically "negative infinity"; return on overflow |
number.positive_infinity |
specifically "positive infinity"; returns |
number.epsilon |
difference between one and the smallest VA on overflow Lue greater than one, can be represented as a number . |
number.min_safe_integer |
javascript minimum security integer. |
number.max_safe_integer |
javascript maximum security integer. |
methods for numbers
method |
Description |
number.parsefloat () |
parses string arguments into floating-point numbers, Same as the global parsefloat () /code> function. |
number.parseint () |
parses a string argument and returns an integer of the spec ified Radix or Base. Same as the global parseint () function. |
number.isfinite () |
Determines whether the value passed is a finite number. |
number.isinteger () |
Determines whether the value passed is an integer. |
number.isnan () |
Determines whether the value passed is NaN . More robust version of the original global IsNaN () . |
number.issafeinteger () |
Determines whether the passed value is a safe integer. |
The type of a number provides methods in different formats to retrieve information from a numeric object. The following table summarizesNumber.prototype的方法。
Methods of
Number.prototype
Method |
Description |
toExponential() |
Returns a string in exponential form of a number, such as: 1.23e+2 |
toFixed() |
Returns the representation of the specified number of decimal digits, var a=123,b=a.tofixed (2)//b= "123.00" |
toPrecision() |
Returns a number that specifies the Precision. In the following example, in a=123, 3 is forced to disappear due to precision limitations var a=123,b=a.toprecision (2)//b= "1.2e+2" |
Math
ObjectEDIT
There Math
are also properties and methods for the built-in math common items and Functions. For example, Math对象的
PI
a property will have a property value of pi (3.141 ...), and you can call it like this:
Math.PI
similarly, the standard math function is also the method of Math. These include trigonometric functions, logarithmic, exponential, and other Function. For example, if you want to use trigonometric functions sin
, you can write:
Math.sin(1.56)
It is important to note that all trigonometric parameters of math are in Radians.
The following table summarizes the Math
methods of the Object.
Methods
Math
of
Method |
Description |
abs() |
Absolute |
sin() , cos() ,tan() |
Standard trigonometric functions; radians |
asin() , acos() , atan() ,atan2() |
Inverse trigonometric function The return value is radians |
sinh() , cosh() ,tanh() |
Double-curvature Trigonometric functions; The return value is Radians. |
asinh() , acosh() ,atanh() |
Inverse hyperbolic trigonometric functions; The return value is Radians. |
pow() , exp() , expm1() , log10() ,log1p() ,log2()
|
Exponential and logarithmic functions |
floor() ,ceil() |
Returns the Maximum/minimum integer less than/greater than or equal to the parameter |
min() ,max() |
Returns Lesser or greater (respectively) of comma separated list of numbers arguments |
random() |
Returns the random number between 0 and 1. |
round() , fround() , trunc() , |
Rounding and truncation functions |
sqrt() , cbrt() ,hypot() |
Square root, Cubic root, squared parameter, and 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() |
In a 32-bit 2 binary representation, The number of 0 Starts. The result of the c-like 32-bit multiplication of the Arguments. |
Unlike other objects, you cannot create a math object of your Own. You can only use the built-in math Object.
Date ObjectEDIT
JavaScript does not have a date data type. But you can use Date
objects and their methods in your program to handle dates and Times. The Date object has a number of methods for setting, getting, and manipulating Dates. It does not contain any Attributes.
JavaScript processes date data similar to Java. The two languages have many of the same methods of processing dates, and they all store data types in milliseconds since 00:00:00 January 1, 1970.
Date
The range of objects is 100,000,000 days before and after the relative distance from UTC January 1, 1970.
Create a date Object:
var dateObjectName = new Date([parameters]);
The Dateobjectname object here is the name of the created date object, which can be a new object or a property of another object that already exists.
Calling a Date object without using the New keyword will simply convert the supplied date object to a string Representation.
The arguments in the front of the syntax can be any one of the following:
- No parameters: create Today's date and time, for example:
today = new Date();
.
- A string that represents the date in the following format: "month day, year: minute: seconds." for example:
var Xmas95 = new Date("December 25, 1995 13:30:00")。
If you omit hours, minutes, seconds, Their values will be set to 0.
- A collection of integer values for a year, month, day, for Example:
var Xmas95 = new Date(1995, 11, 25)。
- A collection of years, months, days, hours, minutes, seconds, for example:
var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);
.
Date对象的方法
The Date object methods that handle datetime are divided into the following categories:
- The set method, which sets the date and time value of the date Object.
- The "get" method that gets the date and time value of the date Object.
- The "to" method that returns the string-formatted value of the date Object.
- Parse and UTC methods for parsing a date string.
With the "get" and "set" methods, you can set and get seconds, minutes, hours, days, weeks, months, and years, respectively. Here's a getday method that can be put back into the week, but there is no corresponding Setday method used to set the week, because the week thing is automatically set. These methods use integers to represent the following values:
- seconds, Minutes: 0 to 59
- Hours: 0 to 23
- Week: 0 (Sunday) to 6 (Saturday)
- Date: 1 to 31
- Month: 0 (January) to 11 (December)
- Year: number of years starting from 1900
For example, Suppose you define the following date:
var Xmas95 = new Date("December 25, 1995");
Then Xmas95.getMonth()
returns one, and Xmas95.getFullYear()
returns 1995.
getTime
And setTime
methods are very useful for comparing dates. getTime
The method returns the number of milliseconds from 00:00:00 January 1, 1970.
For example, The following code shows the remaining days of the Year:
var today = new Date();var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // 设置日和月,注意,月份是0-11endYear.setFullYear(today.getFullYear()); // 把年设置为今年var msPerDay = 24 * 60 * 60 * 1000; // 每天的毫秒数var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay;var daysLeft = Math.round(daysLeft); //返回这一年剩下的天数
In this example, we create a Date object that contains Today's dates, and then we create a Date object named endyear, set the year to the current year, and then use the number of milliseconds per day and gettime to get the number of milliseconds for today and the end Respectively. Calculate the number of days to the end of today, and finally round out the remainder of the year.
The parse method is useful for assigning values from a date string to an existing date object, for example: The following code assigns a date value to the Ipodate object using parse and Settime:
var IPOdate = new Date();IPOdate.setTime(Date.parse("Aug 9, 1995"));
Example:
In the example below, the Jsclock () function returns the time in a digital clock format:
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函数首先创建了一个叫做time的新的Date对象,因为没有参数,所以time代表了当前日期和时间。然后调用了
getHours
, getMinutes以及getSeconds方法把当前的时分秒分别赋值给了hour
, minute
,second。
The next 4 sentences create a string on the basis of time, the first sentence creates a variable temp, and is assigned by a conditional expression, if the hour is greater than 12, the hour - 12
other is hour, unless hour is 0, in which case it becomes 12.
The next statement spliced the minute
values to thetemp后。如果minute小于10,条件表达式就会在minute前边加个0,其他情况下加一个分号。然后按同样的方式在temp后拼接上了秒。
finally, if the hour is 12 or greater, the conditional expression will be stitched "p.m." after temp, otherwise stitching "a.m.".
«previous page
Numbers and date types in JavaScript