Preface
Before starting to learn, what we want to tell you is that this article is a JavaScript
of the "data type" part of 0609e7b628f8fe language knowledge. If you have mastered the following knowledge items, you can skip this section and go directly to the topic exercise
- Boolean type
- null type
- undefined type
- Number type
- String type
- BigInt type
- Symbol type
- Object type
- Numerical type conversion
If you have forgotten some parts, 👇🏻 is ready for you!
Summary
Boolean type
Boolean
(Boolean) type is ECMAScript
of the most frequently used types in 0609e7b628fa3e, with two literal values: true
and false
. These two Boolean values are different from the numeric value, so true
not equal to 1
, and false
not equal to 0
.
let xhsFound = true
let xhsLost = false
Note: boolean literalstrue
andfalse
are case sensitive (that is,False
andTrue
cannot be used).
Boolean() transformation function
This function can convert a value of another type to a Boolean value.
let message = 'Hello world!'
let messageAsBoolean = Boolean(message) // true
Boolean()
transformation function can be called on any type of data, and it always returns a Boolean value. The rules for what value can be converted to true
or false
depend on the data type and the actual value.
Conversion rules between different types and Boolean values
type of data | Converted to the value true | Converted to the value false |
---|---|---|
Boolean | true | false |
String | Non-empty string | "" (empty string) |
Number | Non-zero values (including infinite values) | 0, NaN (see related content below) |
Object | Any object | null |
Undefined | N/A (not exist) | undefined |
It is very important to understand the above conversion, because if
will automatically perform the conversion of other types of values to Boolean values, for example:
let message = 'Hello world!'
if (message) {
console.log('Value is true')
}
In this example, console.log
will output the string "Value is true"
because the string message
will be automatically converted to the equivalent Boolean value true
. Because of this automatic conversion, it is very important to understand what variables are used in the control statement. The wrong use of objects instead of Boolean values can significantly change the execution logic of the application.
null type
null
type also has only one value, the special value null
. Logically speaking, the null
represents a null object pointer, which is typeof
passing a null
will return "object"
.
let xhsObject = null
console.log(typeof xhsObject) // "object"
When defining the variable that will save the object value in the future, it is recommended to use null
to initialize, and do not use other values. In this way, as long as you check null
you can know whether this variable was later given a reference to an object.
if (xhsObject != null) {
// xhsNull 是一个对象的引用
}
undefined
value of null
is derived from the ECMA-262
defines them as ostensibly equal
console.log(null == undefined) // true
Using the equal operator ( ==
) to compare null
and undefined
always returns true
. But be aware that this operator will convert its operands for comparison.
Even if null
and undefined
are related, their uses are completely different. It is never necessary to explicitly set the variable value to undefined
. But null
is not the case. At any time, as long as the variable wants to save the object, and there is no object to save at the time, it is necessary to fill the variable null
In this way, null
being a null object pointer undefined
.
null
is a false value. Therefore, if necessary, it can be detected in a more concise way. But keep in mind that there are many other possible values that are also false. So you must make it clear that what you want to detect is null
, not just a false value.
let xhsMessage = null
let xhsAge
if (xhsMessage) {
// 这个块不会执行
}
if (!xhsMessage) {
// 这个块会执行
}
if (xhsAge) {
// 这个块不会执行
}
if (!xhsAge) {
// 这个块会执行
}
undefined type
undefined
type has only one value, which is the special value undefined
. When var
or let
but not initialized, it is equivalent to assigning a value undefined
let xhsMessage
console.log(xhsMessage == undefined) // true
In this example, the variable xhsMessage
was not initialized when it was declared. When comparing it with undefined
, the two are equal.
let xhsMessage = undefined
console.log(xhsMessage == undefined) // true
Here, the variable message
explicitly initialized undefined
But this is unnecessary, because by default, any uninitialized variable will get the value of undefined
Note that in general, you never need to explicitly set the value ofundefined
The purpose of adding this special value is to formally clarifynull
) and an uninitialized variable.
Note that there is a difference between variables undefined
Consider the following example:
let xhsMessage // 这个变量被声明了,只是值为 undefined
// 确保没有声明过这个变量
// let xhsAge
console.log(xhsMessage) // "undefined"
console.log(xhsAge) // 报错
In the above example, the first console.log
will indicate the value of the message
"undefined"
. The second console.log
will output the value of an undeclared variable age
, which will cause an error. For undeclared variables, only one useful operation can be performed, which is to call typeof
. delete
on undeclared variables will not report an error, but this operation is useless, in fact, an error will be thrown in strict mode.)
typeof
on an uninitialized variable, the returned result is "undefined"
, but when calling it on an undeclared variable, the returned result is still "undefined"
, which is a bit incomprehensible.
let xhsMessage // 这个变量被声明了,只是值为 undefined
// 确保没有声明过这个变量
// let xhsAge
console.log(typeof xhsMessage) // "undefined"
console.log(typeof xhsAge) // "undefined"
Whether it is declared or undeclared, typeof
returns the string "undefined"
. Logically speaking, this is correct, because although strictly speaking these two variables are fundamentally different, neither of them can perform actual operations.
Note: Even uninitialized variables will be automatically assigned theundefined
, but we still recommend to initialize the variables while declaring them. In this way, whentypeof
returns"undefined"
, you will know that it is because the given variable has not been declared, rather than declared but not initialized.
undefined
is a false value. Therefore, if necessary, it can be detected in a more concise way. But keep in mind that there are many other possible values that are also false. So be sure to make it clear that what you want to detect is undefined
, not just a false value.
let xhsMessage // 这个变量被声明了,只是值为 undefined
// xhsAge 没有声明
if (xhsMessage) {
// 这个块不会执行
}
if (!xhsMessage) {
// 这个块会执行
}
if (xhsAge) {
// 这里会报错
}
Number type
Number
type uses the IEEE 754
format to represent integer and floating-point values (also called double-precision values in some languages).
Decimal integer
let xhsIntNum = 55 // 整数
You can also use octal integer (with 8
as the base) or hexadecimal (with 16
as the base) literal representation.
Octal integer
For octal literals, the first digit must be zero ( 0
), and then the corresponding octal digit (value 0~7
). If the number contained in the literal exceeds the expected range, the prefix zero will be ignored, and the following sequence of numbers will be treated as a decimal number.
let xhsOctalNum1 = 070 // 八进制的 56
let xhsOctalNum2 = 079 // 无效的八进制值,当成 79 处理
let xhsOctalNum3 = 08 // 无效的八进制值,当成 8 处理
Hexadecimal integer
To create a hexadecimal literal, you must prefix the real value with 0x
(case sensitive), followed by the hexadecimal number ( 0~9
and A~F
). Letters in hexadecimal numbers can be uppercase or lowercase.
let xhsHexNum1 = 0xa // 十六进制 10
let xhsHexNum2 = 0x1f // 十六进制 31
Note
- Values created in octal and hexadecimal formats are treated as decimal values in all mathematical operations.
- Due to
JavaScript
saves values, there may be positive zeros (+0
) and negative zeros (-0
) in practice. Positive zero and negative zero are considered equivalent in all cases, here is a special explanation.
Floating point value
To define a floating point value, the value must include a decimal point, and there must be at least one digit after the decimal point. Although it is not necessary to have an integer before the decimal point, it is recommended to add it.
let xhsFloatOne = 1.11111
let xhsFloatTwo = 0.11111
let xhsFloatThree = 0.11111 // 有效,不推荐
Because the memory space used to store floating-point values is twice that stores integer values, ECMAScript
always tries to convert the value to an integer. When there is no number after the decimal point, the value becomes an integer.
let xhsFloatOne = 1 // 小数点后面没有数字,当成整数 1 处理
let xhsFloatTwo = 2.0 // 小数点后面是零,当成整数 2 处理
For very large or very small values, floating-point values can be expressed in scientific notation. Scientific notation is used to express a value that should be multiplied by a given power of 10
ECMAScript
of scientific notation in 0609e7b6290130 requires a value (integer or floating point) followed by an uppercase or lowercase letter e
, plus a power 10
to be multiplied by.
let xhsFloat = 3.125e4 // 等于 31250
Scientific notation can also be used to represent very small values, such as 0.000 000 000 000 000 03
. This value can be expressed as 3e-17
in scientific notation.
The accuracy of floating-point values is up to 17
decimal places, but it is far less accurate than integers in arithmetic calculations. For example, 0.1
plus 0.2
obtained not 0.3
. Due to such minor rounding errors, it is difficult to test specific floating-point values.
if (a + b == 0.3) {
//这样判断是错误的
// 0.1 + 0.2 = 0.300 000 000 000 000 04
console.log('输出 0.3 .')
}
0.3
whether the sum of the two values is equal to 0609e7b62901af. If the two values are 0.05
and 0.25
, or 0.15
and 0.15
, then there is no problem. But if it is 0.1
and 0.2
, as mentioned before, the test will fail. So never test for a particular floating point value.
Range of values
Maximum and minimum
Due to memory limitations, ECMAScript
does not support all values in the world.
- The most
value is stored in
Number.MIN_VALUE
, this value is5e-324
- The largest
is stored in
Number.MAX_VALUE
, which is1.797 693 134 862 315 7e+308
Infinity and infinitesimal
If a calculated numerical result exceeds the expressible range, then this numerical value will be automatically converted to a special Infinity
(infinite) value.
- Any negative numbers that cannot be represented are represented by
-Infinity
(negative infinity) - Any positive number that cannot be represented is represented by
Infinity
(positive infinity).
isFinite() function
Used to confirm whether a value is within a limited numerical range (that is, between the maximum value and the minimum value), not false
, and then display true
let xhsResult = Number.MAX_VALUE + Number.MAX_VALUE
console.log(isFinite(xhsResult)) // false
note
- If the calculation returns
positive Infinity or
negative Infinity, the value cannot be used in any further calculations. This is because
Infinity
has no numerical representation available for calculation. - Using
Number.NEGATIVE_INFINITY
andNumber.POSITIVE_INFINITY
can also get positive and negativeInfinity
. That's right, the values contained in these two attributes are-Infinity
andInfinity
respectively. - Although calculations beyond the limited numerical range are rare, they are still possible. Therefore, when calculating very large or very small values, it is necessary to monitor whether the calculation result is out of range.
NaN
There is a special value called NaN
, which means "not a value" ( Not a Number
), which is used to indicate that the operation to return a value failed (instead of throwing an error). For example, 0
in other languages usually results in an error, thus halting code execution. But in ECMAScript
, 0
, +0
or -0
will return NaN
console.log(0 / 0) // NaN
console.log(-0 / +0) // NaN
If the numerator is a value other 0
0
or unsigned 0
, it will return Infinity
or -Infinity
:
console.log(1 / 0) // Infinity
console.log(1 / -0) // -Infinity
Unique properties of NaN
- Any
NaN
always returnsNaN
(such asNaN/10
), which may be a problem in continuous multi-step calculations NaN
not equal to any valueNaN
For example, the following comparison operation will returnfalse
:
console.log(NaN == NaN) // false
isNaN() function
This function receives a parameter, which can be any data type, and judges whether this parameter is "not a value". This function will try to convert the passed parameter into a numeric value. false
if it can be converted to a numeric value, such as a string of "1"
or a Boolean value. Values that cannot be converted to numeric values return true
.
console.log(isNaN(NaN)) // true
console.log(isNaN(1)) // false,1 是数值
console.log(isNaN('1')) // false,可以转换为数值 1
console.log(isNaN('blue')) // true,不可以转换为数值
console.log(isNaN(true)) // false,可以转换为数值 1
Note: is not common,isNaN()
can be used for test objects. At this point, thevalueOf()
method of the object will be called first, and then it will be determined whether the returned value can be converted into a numeric value. If not, call thetoString()
method and test its return value.
String type
String
(string) data type represents a sequence of Unicode
""
with double quotes (0609e7b629054e ), single quotes ( ''
), or back quotes (
`` ).
let xhsFirstName = 'John'
let xhsLastName = 'Jacob'
let xhsLastName = `Jingleheimerschmidt`
let xhsError = 'Nicholas"; // 语法错误:开头和结尾的引号必须是同一种
Character literal
grammar
A literal is a constant defined by a grammatical expression, or a constant defined by a word expression composed of certain words.
The string data type contains some character literals, which are used to represent non-printing characters or characters for other purposes.
Literal | meaning |
---|---|
\n | Wrap |
\t | tabulation |
\b | backspace |
\r | Carriage return |
\f | Page change |
\ | Backslash (\) |
\' | Single quotation mark ('), used when the string is marked with single quotation marks, such as'He said, \'hey.\'' |
\" | Double quotation marks ("), used when the string is marked with double quotation marks, such as "He said, \"hey.\"" |
\` | Backticks (\`), used when the string is marked with backticks, such as \` He said, \` hey.\`` |
\xnn | represented by hexadecimal encoding nn n are hexadecimal digits 0~F), for example \x41 is equal to "A" |
\unnnn | Unicode characters represented by hexadecimal code nnnn n are hexadecimal numbers 0~F), for example \u03a3 is equal to the Greek character "Σ" |
These character literals can appear anywhere in the string and can be interpreted as a single character:
let text = 'This is the letter sigma: \u03a3.'
In this example, even if it contains 6
characters long, the variable text
is still 28
characters long. Because the escape sequence represents one character, it is only counted as one character.
console.log(text.length) // 28 字符串的长度获取
This attribute returns 16
characters in the string.
Note: If the string contains double-byte characters, length
attribute may not be the exact number of characters.
Characters of strings
Strings are immutable, meaning that once they are created, their value cannot be changed. To modify the string value in a variable, you must first destroy the original string, and then save another string containing the new value to the variable.
let lang = 'Java'
lang = lang + 'Script'
Here, the variable lang
initially contains the character string "Java"
. Then, lang
was redefined to include "Java"
and "Script"
, which is also "JavaScript"
. The whole process will first allocate a space enough to hold 10 characters, and then fill it with "Java"
and "Script"
. Finally, the original strings "Java"
and "Script"
, because these two strings are useless.
String interpolation
One of the most commonly used features of template literals is to support string interpolation, that is, one or more values can be inserted in a continuous definition. Technically speaking, the template literal is not a string, but a special kind of JavaScript
syntactic expression, but it is a string after evaluation. Template literals are immediately evaluated and converted to string instances when they are defined, and any inserted variables will also take values from their closest scope.
String interpolation is achieved by using a JavaScript
expression ${}
let value = 5
let exponent = 'second'
// 以前,字符串插值是这样实现的:
let interpolatedString = value + ' to the ' + exponent + ' power is ' + value * value
// 现在,可以用模板字面量这样实现:
let interpolatedTemplateLiteral = `${value} to the ${exponent} power is ${value * value}`
console.log(interpolatedString) // 5 to the second power is 25
console.log(interpolatedTemplateLiteral) // 5 to the second power is 25
All inserted values will be coerced into strings toString()
JavaScript
expression can be used for interpolation.
- Nested template strings do not need to be escaped:
console.log(`Hello, ${`World`}!`) // Hello, World!
toString()
is called when the expression is converted to a string:
let foo = { toString: () => 'World' }
console.log(`Hello, ${foo}!`) // Hello, World!
- Functions and methods can be called in interpolation expressions:
function capitalize(word) {
return `${word[0].toUpperCase()}${word.slice(1)}`
}
console.log(`${capitalize('hello')}, ${capitalize('world')}!`) // Hello, World!
Convert other types to strings
There are two ways to convert a value to a string. The first is to use the toString()
method that almost all values have. The only purpose of this method is to return the string equivalent of the current value.
let xhsAge = 11
let xhsAgeAsString = xhsAge.toString() // 字符串"11"
let xhsFound = true
let xhsFoundAsString = xhsFound.toString() // 字符串"true"
toString()
method can be found in numeric values, boolean values, objects, and string values. (Yes, string values also have a toString()
method, which simply returns a copy of itself.) null
and undefined
values do not have a toString()
method.
In most cases, toString()
does not receive any parameters, and returns decimal by default. You can also set the hexadecimal number through parameters.
let xhsNum = 10
console.log(xhsNum.toString()) // "10"
console.log(xhsNum.toString(2)) // "1010"
console.log(xhsNum.toString(8)) // "12"
console.log(xhsNum.toString(10)) // "10"
console.log(xhsNum.toString(16)) // "a"
Note that the output by default (without passing parameters) is the same as the result obtained by 10
If you are not sure whether a value is null
or undefined
, you can use the String()
transformation function, which will always return a string representing the value of the corresponding type. String() function follows the following rules.
- If the value has a
toString()
method, call this method (without passing parameters) and return the result. - If the value is
null
, return"null"
. - If the value is
undefined
, return"undefined"
.
let xhsValue1 = 10
let xhsValue2 = true
let xhsValue3 = null
let xhsValue4
console.log(String(xhsValue1)) // "10"
console.log(String(xhsValue2)) // "true"
console.log(String(xhsValue3)) // "null"
console.log(String(xhsValue4)) // "undefined"
Here shows the 4
case converted to a string of values: value , Boolean , null and undefined .
The conversion result of value and boolean value the same as toString()
Because null
and undefined
do not have the toString()
method, the String()
method directly returns the literal text of these two values.
Note: uses the plus operator to add an empty string "" to a value, and it can also be converted to a string
BigInt type
BigInt
is a built-in object that provides a way to represent integers 2^53 - 1
This was originally Javascript
can be used Number
largest digital representation. BigInt
can represent an arbitrarily large integer.
description can be used to define a BigInt
n
after an integer number, such as: 10n
, or call the function BigInt()
.
const theBiggestInt = 9007199254740991n
const alsoHuge = BigInt(9007199254740991)
// ↪ 9007199254740991n
const hugeString = BigInt('9007199254740991')
// ↪ 9007199254740991n
const hugeHex = BigInt('0x1fffffffffffff')
// ↪ 9007199254740991n
const hugeBin = BigInt('0b11111111111111111111111111111111111111111111111111111')
// ↪ 9007199254740991n
It is similar to Number
in some respects, but there are also several key differences: it cannot be used for Math
in the 0609e7b6290bbe object; it cannot be Number
instance, and the two must be converted to the same type. Be careful when converting the two types back and forth, because the BigInt
variable may lose precision when it is converted to the Number
Symbol type
symbol
is a basic data type ( primitive data type
). Symbol()
function returns symbol
, which has static properties and static methods. Its static properties will expose several built-in member objects; its static methods will expose the global symbol
registration, which is similar to the built-in object class, but it is not complete as a constructor because it does not support syntax: "new Symbol()"
.
Each from Symbol()
returned symbol
values are unique. A symbol
can be used as an identifier for an object property; this is the only purpose of this data type.
grammar
parameter description optional
Symbol([description])
Optional, string type. The description of symbol
can be used for debugging but not for accessing symbol
itself.
description
Symbol()
directly to create a new symbol
type, and use an optional string as its description.
var sym1 = Symbol()
var sym2 = Symbol('foo')
var sym3 = Symbol('foo')
The above code creates three new symbol
types. Note that Symbol("foo")
will not force the string “foo”
converted to symbol
type. It creates a new symbol
type every time:
Symbol('foo') === Symbol('foo') // false
The following new
operator will throw the TypeError
error:
var sym = new Symbol() // TypeError
This prevents the creation of an explicit Symbol
wrapper object instead of a Symbol
value. Creating an explicit wrapper object around primitive data types is no longer supported starting ECMAScript 6
However, the existing original wrapper objects, such as new Boolean
, new String
and new Number
, can still be created due to legacy reasons.
If you really want to create a Symbol
wrapper object ( Symbol wrapper object
), you can use the Object()
function:
var sym = Symbol('foo')
typeof sym // "symbol"
var symObj = Object(sym)
typeof symObj // "object"
Object type
ECMAScript
are actually a collection of data and functions. The object is created by the new
operator followed by the name of the object type. Developers can Object
, and then add properties and methods to the object.
let xhsO = new Object()
ECMAScript
in Object
is the base class from which other objects are derived. All properties and methods of type Object
Each Object
instance has the following properties and methods.
constructor
: The function used to create the current object. In the previous example, the value of this attribute is theObject()
function.hasOwnProperty(*propertyName*)
: used to determine whether the given attribute exists on the current object instance (not the prototype). The attribute name to be checked must be a string (such aso.hasOwnProperty("name")
) or a symbol.isPrototypeOf(*object*)
: Used to determine whether the current object is the prototype of another object.propertyIsEnumerable(*propertyName*)
: used to determine whether a given attribute can befor-in
statement. LikehasOwnProperty()
, the attribute name must be a string.toLocaleString()
: Returns the string representation of the object, which reflects the localized execution environment where the object is located.toString()
: Returns the string representation of the object.valueOf()
: Returns the character string, numeric value or Boolean value corresponding to the object. Usually the same as the return value oftoString()
Because ECMAScript
the Object
is the base class for all objects, any object has these properties and methods.
Numerical type conversion
There are 3 functions to convert non-numerical values to numerical values: Number()
, parseInt()
and parseFloat()
. Number()
is a transformation function, which can be used for any data type. The latter two functions are mainly used to convert character strings to numeric values. For the same parameter, the operations performed by these 3 functions are also different.
Number() function
The conversion is performed based on the following rules.
- Boolean value,
true
converted to1
,false
converted to0
. - Value, return directly.
null
, return0
.undefined
, returnNaN
.String, the following rules apply.
- If the string contains numeric characters, including plus and minus signs in front of the numeric characters, it is converted to a decimal value. Therefore,
Number("1")
returns1
,Number("123")
returns123
, andNumber("011")
returns11
(ignoring the preceding zero). - If the string contains a valid floating-point value format such as
"1.1"
, it will be converted to the corresponding floating-point value (again, the leading zero is ignored). - If the string contains a valid hexadecimal format such as
"0xf"
, it will be converted to a decimal integer value corresponding to the hexadecimal value. - If it is an empty string (without characters),
0
is returned. - If the string contains characters other than the above,
NaN
is returned.
- If the string contains numeric characters, including plus and minus signs in front of the numeric characters, it is converted to a decimal value. Therefore,
- Object, call the
valueOf()
method, and convert the returned value according to the above rules. If the conversion result isNaN
, call thetoString()
method, and then convert according to the rules of the conversion string.
let xhsNum1 = Number('Hello world!') // NaN
let xhsNum2 = Number('') // 0
let xhsNum3 = Number('000011') // 11
let xhsNum4 = Number(true) // 1
parseInt() function
- The first space of the string will be ignored, and the conversion will start from the first non-space character
- If the first character is not a numeric character, plus or minus sign,
parseInt()
immediately returnsNaN
- If the first character is a numeric character, a plus sign, or a minus sign, each character is continuously checked until the end of the string or a non-numeric character is encountered. For example,
"1234blue"
will be converted to1234
because"blue"
will be completely ignored. Similarly,"22.5"
will be converted to22
because the decimal point is not a valid integer character.
Assuming that the first character in the string is a numeric character, the parseInt()
function can also recognize different integer formats (decimal, octal, hexadecimal). In other words, if the string starts with "0x"
, it will be interpreted as a hexadecimal integer. If the string starts with "0"
and immediately follows a numeric character, it will be interpreted as an octal integer by some implementations in non-strict mode.
let xhsNum1 = parseInt('1234blue') // 1234
let xhsNum2 = parseInt('') // NaN
let xhsNum3 = parseInt('0xA') // 10,解释为十六进制整数
let xhsNum4 = parseInt(22.5) // 22
let xhsNum5 = parseInt('70') // 70,解释为十进制值
let xhsNum6 = parseInt('0xf') // 15,解释为十六进制整数
parseInt()
also receives the second parameter, which is used to specify the base number. You can omit the previous 0x
or 0
let xhsNum = parseInt('0xAF', 16) // 175
let xhsNum1 = parseInt('AF', 16) // 175
let xhsNum2 = parseInt('AF') // NaN
With the second parameter, the type of result obtained after conversion can be greatly expanded.
let xhsNum1 = parseInt('10', 2) // 2,按二进制解析
let xhsNum2 = parseInt('10', 8) // 8,按八进制解析
let xhsNum3 = parseInt('10', 10) // 10,按十进制解析
let xhsNum4 = parseInt('10', 16) // 16,按十六进制解析
Note: most cases, 1609e7b6291460 should be parsed as decimal numbers. At this time, the second parameter must be passed in 10
.
parseFloat() function
The function of this function is similar to the parseInt()
function, which starts from the position 0
to detect each character. Similarly, it is parsed to the end of the string or to an invalid floating-point numeric character. This means that the decimal point that appears for the first time is valid, but the decimal point that appears for the second time is invalid, and the remaining characters of the string will be ignored. Therefore, "22.34.5"
will be converted to 22.34
.
note
- It always ignores the zero at the beginning of the string
- Hexadecimal values will always return
0
- If the string represents an integer (there is no decimal point or there is only a zero after the decimal point),
parseFloat()
returns an integer
let xhsNum1 = parseFloat('1234blue') // 1234,按整数解析
let xhsNum2 = parseFloat('0xA') // 0
let xhsNum3 = parseFloat('22.5') // 22.5
let xhsNum4 = parseFloat('22.34.5') // 22.34
let xhsNum5 = parseFloat('0908.5') // 908.5
let xhsNum6 = parseFloat('3.125e7') // 31250000
Self-test
One: What is the difference between null and undefined?
Two: The following code, which result returns NaN()
A. let a = Number('')
B. let b = Number('xhs')
C. let c = Number(true)
D. let d = Number(120);
3: What does the following code output?
let a = 12
let b = false
let c = null
let d = undefined
console.log(typeof a.toString())
console.log(typeof b.toString())
console.log(String(c))
console.log(String(d))
Problem analysis
One,null
and undefined
are basic data types, and they all have only one value in themselves, that is, null
and undefined
. undefined means undefined, null means empty object.
null == undefined // true
null === undefined // false
Number(null) // 0
Number(undefined) // NaN
two,
Answr:B
Number()
function in numeric type conversion is used here
A is an empty string, and the returned value is 0
after conversion. Other types in the B string are converted to NaN
. C true
will first be converted to 1
and then converted to a numeric value. D is a normal numeric value and returns the original value, so 120
three,toString()
method converts all values into character strings and outputs them. However null
and undefined
not toString()
methods may be used String()
directly into a string.
// 'string'
// 'string'
// 'null'
// 'undefined'
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。