This is “review the old to know the new series summary”, start to talk about data structure this most basic most basic things, may be many students did not seriously study, write the place is not in place, please greatly more advice!
JavaScript is an amazing language, and even data types are an introductory subject that you can learn a lot about
- This article refers to the latest
ECMAScript2022
Specification, attached link- ECMAScript® 2022 Language Specification (tc39.es)
I. Classification of data types
JavaScript data types can be divided into seven kinds of basic data types (Undefined, Null, Boolean, Number, String, Symbol, BigInt) and one kind of complex data types (Object)
- Primitive data types hold raw values
primitive value
- Complex data types hold objects
an object
, which is a reference valuereference value
, where there is a prototype objectprototype object
, may be empty (such as a top-level objectObject
theprototype object
That is empty{}
)
1. typeof
The operator
Typeof is not a function, but an operator followed by an operand (an expression representing an object or primitive value) that returns the typeof the operand
// The return value is a string
typeof operand
typeof(operand)
Copy the code
Special: Notice the type returned hereIs not
The following table summarizes the one-to-one correspondence between data types
type | Value for | Typeof Operation result |
---|---|---|
Undefined | Undefined (only value) | “undefined” |
Null | Null (only value) | “object” |
Boolean | True,false(only two values) | “boolean” |
Number | – 0, + 0,1,2.1, Infinity and NaN… | “number” |
BigInt | 10n,20n… | “bignit” |
String | “”,”jack”,”it is a joke”… | “string” |
Symbol | Symbol(“aaa”)… | “symbol” |
The host object | Person creates the object Person1 | “Person” depends on the implementation |
The Function object | const foo = function(){} | “function” |
Any other object | Array | Date | RegExp | Set | WeakSet Map for | | WeakMap | Object | original value packaging Object… | “object” |
2. Undefined
There is only one value, undedined
2.1 Declare uninitialized
let a
console.log(a) //undefined
console.log(typeof a) //undefined
Copy the code
2.2 An error will be reported if you use it without declaring it
console.log(b) //ReferenceError: b is not defined
console.log(typeof b) //undefined
Copy the code
Suggestion: It is recommended that uninitialized variables be initialized at the same time they are declared, even though they are automatically assigned a undefined value. This way, when typeof returns “undefined”, you know that it is because the given variable is undeclared, rather than declared but uninitialized
2.3 undefined
Is a false value
console.log(Boolean(undefined)) //false
Copy the code
3. Null
There is only one value, null
3.1 represents a null object pointer
console.log(typeof obj) //object
Copy the code
3.2 null
Is a false value
console.log(Boolean(null)) //false
Copy the code
3.3 undefined
isnull
Derived usage of
console.log(undefined= =null) //true
Copy the code
4. Boolean
There are only two values true\false
4.1 True
andFalse
It’s not a Boolean, it’s an identifier
4.2 Other Types of Booleans
Boolean() is a transformation function that can be used to convert any data type
//1.String
console.log(Boolean(' ')) //false
console.log(Boolean('li')) //true
//2.Number
console.log(Boolean(0)) //false
console.log(Boolean(NaN)) //false
console.log(Boolean(1)) //true
console.log(Boolean(Infinity)) //true
console.log(Boolean(-Infinity)) //true
//3.Object
console.log(Boolean({name: 'li'})) //true
//4.Undefined
console.log(Boolean(undefined)) //false
//5.Null
console.log(Boolean(null)) //false
Copy the code
5. Number
Everyday use of values is not that complicated and generally does not involve many boundary cases
5.1 If the value itself is an integer, 0 after the decimal point is ignored
console.log(3.0) / / 3
Copy the code
5.2 Floating point calculation accuracy loss
It is a common problem with IEEE754 values that you should never determine a particular floating point value
console.log(0.1 + 0.2) / / 0.30000000000000004
Copy the code
5.3 Range of values
The minimum value that ECMAScript can represent is stored in number.min_value, which in most browsers is 5E-324; The maximum value that can be represented is stored in number. MAX_VALUE, which in most browsers is 1.797 693 134 862 315 7e+308. So this is going to be converted to plus Infinity plus Infinity and minus Infinity minus Infinity, and I did an interesting test here.
let max = Number.MAX_VALUE / / 1.7976931348623157 e+308
let a = max + 1
console.log(isFinite(a)) //true
console.log(a) / / 1.7976931348623157 e+308
Copy the code
Analysis: MAX_VALUE = “Infinity”; MAX_VALUE = “Infinity”; MAX_VALUE = “Infinity” How much more can I add to make it Infinity without being ignored?
let max = Number.MAX_VALUE / / 1.7976931348623157 e308
let a291 = max + 1.7976931348623157 e291
let b292 = max + 1.7976931348623157 e292
console.log(isFinite(a291), isFinite(b292)) //true false
console.log(a291, b292) / / 1.7976931348623157 e+308 Infinity
Copy the code
As can be seen: MAX_VALUE is 17 orders of magnitude different from a291, and 16 orders of magnitude different from number. MAX_VALUE is b292, so numbers with a magnitude difference greater than or equal to 17 orders of magnitude will be ignored before number. MAX_VALUE. MAX_VALUE = 16; MAX_VALUE = 16; MAX_VALUE = 16; -infinity same thing, just with a minus sign, minus Infinity.
In the case of number.min_value, this is the smallest Number that can be represented. When tested, it is still number.min_value after subtracting any smaller Number, using isFinite() always returns true
let min = Number.MIN_VALUE
let min1 = min - 5e-500
let min2 = min - 5e-325
console.log(isFinite(min1), isFinite(min2)) //true true
console.log(min1, min2) //5e-324 5e-324
Copy the code
I finally understand what the maximum and minimum values can be expressed. Even if some values are greater than the maximum value and less than the minimum value, they are still the same value after JS calculation. If the value is further larger, it will become Infinity
5.4 Values of Other Types
5.4.1 Number ()
Number is a transformation function that can be used to convert any data type
//null
console.log(Number(null)) / / 0
//undefined
console.log(Number(undefined)) //NaN
//Boolean
console.log(Number(true)) / / 1
console.log(Number(false)) / / 0
Copy the code
The rules for converting strings are a little more special
A few rules summarize this: return 0 for an empty string, NaN for any non-base character, omit 0 before integer and floating point numbers, omit 0 before base numbers, and return NaN for all other cases
console.log(Number(' ')) / / 0
console.log(Number('a11')) //NaN
console.log(Number('011a11')) //NaN
console.log(Number('01.1 a11')) //NaN
console.log(Number('011')) / / 11
console.log(Number('011.1')) / / 11.1
console.log(Number('0b11')) / / 3 binary
console.log(Number('0o11')) / / 9 octal
console.log(Number('0x11')) / / 17 hexadecimal
Copy the code
The valueOf method is called and the above rules are called. If the result of the conversion is NaN, the toString method is called and the string rules are converted. This is the description in the little Red Book. At present, I have not met the situation of NaN transferring to toString again, nor have I thought of relevant examples. If you know, please comment
Let’s look at two examples
//a is an object Boolean{false}. Calling valueOf returns false
let a = new Boolean(' ')
// Equivalent console.log(Number(a.valueof ()))) <=>console.log(Number(false))
console.log(Number()) / / 0
let b = new Date(a)console.log(Number(b))// The current time is the number of milliseconds
Copy the code
5.4.2 parseInt
Two parameters can be accepted. The first parameter is the string to be converted, and the second parameter is the converted base. If the second parameter is present, the base of the first parameter can be omitted, indicating 0b, 0O,0x
The parseInt() function focuses more on whether the string contains a numeric pattern. The first space in the string is ignored, and the first non-space character is converted. If the first character is not a numeric character, plus or minus, parseInt() immediately returns NaN. This means that an empty string also returns NaN(unlike Number(), which returns 0). If the first character is a numeric character, plus or minus, each character in turn is tested until the end of the string, or a non-numeric character is encountered. The parseInt() function can also recognize different integer formats (decimal, octet, hexadecimal)
console.log(parseInt(' ')) //NaN
console.log(parseInt('a1a11')) //NaN
console.log(parseInt('1a11')) / / 1
console.log(parseInt('11.1')) / / - 11
console.log(parseInt('0x13')) / / 19
console.log(parseInt('13'.16)) / / hexadecimal 19
Copy the code
5.4.3 parseFloat
Similar to parseInt, it only recognizes the first decimal point, does not ignore 0 at the beginning of the string if the value is 0. XXX, and returns 0 if it is a non-decimal number. Therefore, it can only parse decimal values and cannot specify base (base), and returns an integer if there is only one 0 after the decimal point
console.log(parseFloat(' a0.11a')) //NaN
console.log(parseFloat('01.1.1 aa)) / / 1.1 console. The log (parseFloat (' -0.1a. ')) / / 0.1 the console log (parseFloat (' 0b11')) //0
console.log(parseFloat(' 02.0a')) / / 2Copy the code
5.5 NaN
The operation to return a number failed
console.log(0 / 0) //NaN
console.log(1 / 0) //Infinity
console.log(1 / -0) //-Infinity
Copy the code
-
Any operation that involves NaN returns NaN
-
NaN is not equal to any value including NaN
console.log(NaN= =NaN) //false Copy the code
-
IsNaN (param) is used to test if the parameter is not a value. After passing a value to isNaN, the function attempts to convert it to a value, returning false if it can be converted to a value, and true if it cannot
// String values such as '10.1' or booleans can be converted to numeric values // Any value that cannot be converted to a numeric value causes the function to return true console.log(isNaN(true)) //1---false console.log(isNaN(false)) //0---false console.log(isNaN('10.1')) / / 10.1 - false console.log(isNaN('1')) //1---false console.log(isNaN(NaN)) //true console.log(isNaN('blue')) //true console.log(isNaN(undefined)) //true console.log(isNaN(null)) //0---false Copy the code
6. BigInt
BigInt is a built-in object. The Typeof operator returns “BigInt”, which is not a reference type, but a stored original value. Using an integer literal followed by an n, or calling BigInt(), cannot be used with the new operator because it does not construct an object instance, not a reference type
//BigIntConstructor. (value: bigint | boolean | number | string): bigint
let a = 1n
let b = BigInt(true)
console.log(typeof a) //bigint
console.log(a, b) //1n 1n
Copy the code
6.1 Operator Operations
The following operators can be used with BigInt: +, -, *, /, **, %. Other than >>> (unsigned right shift) is also supported. Since BigInt is signed, >>> (unsigned right shift) cannot be used for BigInt.
console.log(1n + 1n) //2n
console.log(1n - 2n) //-1n
console.log(1n * 2n) //2n
console.log(5n / 2n) // If 2n is rounded down, the decimal part will be discarded
console.log(1n % 2n) //1n
console.log(3n ** 2n) //9n
console.log('Programmer's favorite number is:'.1n << 10n) // The programmer's favorite number is 1024n
console.log(10n >> 2n) // 2N analysis: 10N/(2n**2n) <=> 10N / 4n <=> 2n
Copy the code
6.2 compare
6.2.1 Loose equality with Number, not strict equality
console.log(1n= =1) //true
console.log(1n= = =1) //false
Copy the code
6.2.2 The value can be compared with Number
console.log(1n < 1) //false
console.log(2n> =2) //true
Copy the code
6.3 the toString and the valueOf
Overriding the corresponding methods on the Object prototype, toString() returns a string in radix, and valueOf() returns the specified bigInt raw value
console.log(1n.toString()) / / 1
console.log(1n.valueOf()) //1n
Copy the code
7. String
This is probably the most frequently used data type, representing zero or more sequences of 16-bit Unicode characters in three ways: double quote “a”, single quote ‘a’, and back quote (‘ ‘).
7.1 Escape Characters
The beginning \ indicates operations such as carriage return, line feed, etc., similar to other programming languages
\ XNN represents the hexadecimal character denoted by nn (where n is the hexadecimal digit 0 to F), for example, \x41 equals “A”
\unnnn indicates Unicode characters in hexadecimal encoding NN (where n is the hexadecimal digits 0 to F). For example, \ u03A3 equals “sigma”, and the Unicode encoding for emoji is E63E to E757
7.2 Other Types are Converted to Strings
7.2.1 String() transformation function
Null \undefined returns null\undefined, respectively. See toString below for other types
console.log(String(null)) //null
console.log(String(undefined)) //undefined
Copy the code
7.2.1 toString () method
Values, bores, objects, and strings are automatically converted into wrapped objects. As we’ll see later, objects call their toString methods directly, overridden or unoverridden. Unoverridden toString returns [object type]
let a = 1
console.log(a.toString()) / / 1
console.log(true.toString()) //true
console.log(false.toString()) //false
/ / object
let obj1 = {
' ': 'a' // The key can be empty, but it is not usually used that way
}
console.log(obj1.toString()) //[object Object]
let obj2 = {
' ': 'obj2'.toString() {
return this[' ']}}console.log(obj2.toString()) //[object Object]
Copy the code
The base can be added when the value is used, that is, a base parameter is added to indicate what base is to be converted
let a = 10
console.log(a.toString()) / / 10
console.log(a.toString(2)) / / 1010
console.log(a.toString(8)) / / 12
console.log(a.toString(16)) //a
Copy the code
7.3 Template Strings
ES6 new syntax, use ** ‘** to represent strings, internal will retain the newline character, can define strings across lines
let s = ` hello`
console.log(s.length) / / 6
console.log(s[0= = ='\n') //true
console.log(s[1= = =' ') //true
Copy the code
7.3.1 Interpolation Syntax
String interpolation is implemented by using JavaScript expressions in ${}, which can be used with any JavaScript expression and will cast the final result to a string
let a = 1
let s = `the number is ${a}`
console.log(s) //the number is 1
Copy the code
7.3.2 Label functions
Tag function tag function
The first argument received: the raw string array, which is an array of strings separated by interpolation syntax, contains the empty strings before and after, and the subsequent argument is the evaluation of each interpolation expression.
function foo(x, y, z) {
console.log(x) //[ 'hello', 'world', '' ]
console.log(y) //second param
console.log(z) //third param
return 'foo function'
}
const res = foo`helloThe ${'second param'}worldThe ${'third param'}`
console.log(res) //foo function
Copy the code
React may be used more efficiently than react
7.3.3 Raw Strings
Raw String content can be retrieved from template strings, including newlines or Unicode characters, using the default label function String.raw. The first argument to the label function has a RAW attribute that retrieves the raw content of each String
function foo(str) {
console.log('The actual string displayed is:')
for (const s of str) {
console.log(s)
}
console.log('The original value is:')
for (const s of str.raw) {
console.log(s)
}
}
foo`\u00a9The ${'none of my business! '}\n`
// The actual string displayed is:
['©', '\n']
/ / ©
// (here is a newline character)
//
// The original value is:
// \u00a9
// \n
Copy the code
8. Symbol
The basic data type, Symbol([description]) function returns a unique value of the Symbol type. Even if the optional descriptor is the same, the generated Symbol is not equal and can be used as an identifier for object properties, which is what this data type is created for.
let s1 = Symbol(a)let s2 = Symbol('foo')
let s3 = Symbol('foo')
console.log(s1, s2, s3) //Symbol() Symbol(foo) Symbol(foo)
console.log(s2 === s3) //false
console.log(s2.description) //foo
Copy the code
8.1 Globally shared Symbol
Use the symbol.for () and symbol.keyfor () methods to create and obtain symbols that can be used across files
let s1 = Symbol.for('foo')
let des1 = Symbol.keyFor(s1)
console.log(des1) //foo
let s2 = Symbol.for('foo')
console.log(s1 === s2) //true
Copy the code
8.2 Use of attribute descriptors in 3
const s1 = Symbol('s1_Symbol')
const s2 = Symbol('s2_Symbol')
const s3 = Symbol('s3_Symbol')
/** * 1. Define literals to use directly, using the calculated attribute */
const obj = {
name: 'dd'.age: 19,
[s1]: 'abc',}/** * 2. Assign the attribute name, using the same assignment method as index */
obj[s2] = 'bcd'
/** * 3. Use object.defineProperty */
Object.defineProperty(obj, s3, {
configurable: true.enumerable: true.writable: true.value: 'cde',})console.log(obj)
/** { name: 'dd', age: 19, [Symbol(s1_Symbol)]: 'abc', [Symbol(s2_Symbol)]: 'bcd', [Symbol(s3_Symbol)]: 'cde' } */
Copy the code
8.3 traversal
Common attributes in objects can be passed in and for… Get in, but the Symbol is more special, can’t get through them, you must use the Object. The getOwnPropertySymbols () method to get, it is a special way.
console.log(Object.getOwnPropertySymbols(obj)) // obj is the obj of 8.2
//[ Symbol(s1_Symbol), Symbol(s2_Symbol), Symbol(s3_Symbol) ]
Copy the code
9. Object
Objects are common by using the new operator followed by the name of an Object type, similar to Java, but different from Java, because JavaScript doesn’t really have the concept of a class. Objects have a lot of properties and methods, and they’ll still have them on any created Object unless they’re overridden. Later review to the prototype prototype chain when more details, common attributes and methods are as follows:
-
Constructor is used to create the current object function
-
HasOwnProperty (propertyName) is used to determine whether a given genus exists on the current object instance (not the prototype)
sex
-
IsPrototypeOf (object) Is used to determine whether the current object is the prototype of another object
-
PropertyIsEnumerable (propertyName) propertyIsEnumerable(propertyName) In traverses
-
ToLocaleString () returns a string representation of the object that reflects its localized execution environment
-
ToString () returns a string representation of the object
-
ValueOf () returns a string, numeric, or Boolean representation of the object, usually the same as toString()
There are too many things to say about the object, so I will write a special article to analyze it in depth
10. Packaging type (left over from history)
What is a package type? If you have learned Java, you may have heard of the concept of autowerism. Javascript provides wrapper reference types for Boolean,Number, and String, which can be used with the new operator. Objects can make full use of its related properties or methods for operation, and basic data types to the original value of the deposit can’t enjoy the dividends, so in order to make we can very convenient operating them, give them to do the packaging, of course, we don’t usually show the use of them, when to use a primitive value method or attribute, the background will help us to create automatically, After use, it will be destroyed automatically, without us to carry out other operations.
let str1 = 'hello world.'
let str2 = str1.toUpperCase() //HELLO WORLD.
/ / equivalent to the
let str1 = new String("hello world.") // Create an instance of String
let str2 = s1.toUpperCase() // Invoke a specific method on the instance
str1 = null // Destroy the instance
Copy the code
2.1 Automatic life flow
An automatically created primitive value wrapper object exists only for the duration of the execution of the line of code accessing it, meaning that attributes and methods cannot be added to the primitive value at run time
let s1 = 'hello world.'
s1.info = 's1'
console.log(s1.info) //undefined
Copy the code
Analysis of the
- The second line creates a String instance and appends the info attribute to it, which will be destroyed as soon as it completes
- Line 3
again
A new instance is created and the info attribute is assigned to it, but no value is assigned and the instance is destroyed as soon as this line of code completes
2.2 Boolean, Number, String
We usually do not display new them, just know there is such a thing, this is a legacy of JavaScript, of course, each wrapped object has some methods or to understand, specific can refer to the MDN document for learning
Link to the JavaScript | MDN (mozilla.org)
All data types are summarized here. There are also some built-in object types, such as Date, RegRex, Set, Map and so on, which are basically the use of SOME API. If there is time in the later period, we will summarize another wave.