Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the knowledge points of JS data type

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "what are the knowledge points of JS data type". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "what are the knowledge points of JS data type" can help you solve the problem.

What are the data types in JavaScript?

The data types defined in the computer world are actually defined to describe the facts that exist in the real world. For example, we use people as an example:

Is there anyone in the room? Here the concept of yes and no is yes or no. In JS, it corresponds to the Boolean type. True means yes, and false means not.

How many people are in the room? The several here represent an order of magnitude concept, which corresponds to the Number type in JS, including integers and floating-point numbers, as well as some special values, such as:-Infinity for negative infinity, + Infinity for positive infinity, NaN for not a number

These people in the room are all my friends. This is a statement, and the information of this text class will be stored as a string, corresponding to the String type in JS.

There is no one in the room. There is no concept of nothing and emptiness here, which can be expressed by both null and undefined in JS.

Everyone in the real world is unique, which corresponds to the Symbol type in JS, which means unique and immutable

The integer represented by Number has a range, and the data out of the range cannot be represented by Number, so a new data type BigInt is proposed in ES10, which can represent any number of integers.

The seven types mentioned above, such as Boolean, Number, String, null, undefined, Symbol and BigInt, are primitive types in JavaScript, and the other is a non-primitive type called object type. For example, a person is an object, and the person has a name, sex, age, etc.

Let person = {name: 'bubuzou', sex:' male', age: 26,} Why distinguish between primitive types and object types? What's the difference between them? Immutability of the original type

Before answering this question, let's take a look at how variables are stored in memory:

Let name1 = 'bubuzou'let name2 = name1.concat (' .com') console.log (name1) / / 'bubuzou'

After executing the above code, we find that the value of the variable name1 remains the same, still bubuzou. This shows that the string is immutable. But if you look at the following code, you will have questions:

Let name1 = 'bubuzou'name1 + =' .com'console.log (name1) / / 'bubuzou.com'

You said the string is immutable, so it's changed now, isn't it? In fact, the value of the variable has changed, but the string that exists in memory remains the same. This involves the storage of variables in memory. In JavaScript, variables are stored in memory in two ways: in the stack and in the heap. So what's the difference between stack memory and heap memory?

Stack memory:

Sequential storage structure, characterized by first-in-first-out. Just like a ping-pong box, the ping-pong ball is put into the box one by one from the outside, and the first one taken out must be the last one put into the box.

Storage space is fixed

The saved value can be operated directly, and the execution efficiency is high.

Heap memory:

Disordered storage structure

Storage space can be changed dynamically

Cannot directly operate its internal storage, it needs to be operated by referencing the address.

Then we can describe what happens when the computer executes this code? First, a variable name1 is defined and assigned a value of bubuzou, which opens up a space in memory to store the string bubuzou, and then the variable points to that memory space. Then execute the second line of code letname2=name1.concat ('.com'). The concatenation operation here actually produces a new string bubuzou.com, so a new block of memory is created for the new string and the defined variable name2 points to this memory address. So we can see that the memory of the whole operation bubuzou is actually unchanged. Even if the name1+='.com' operation is performed in the second piece of code, it is only the variable name1 that points to the new string bubuzou.com. The old string bubuzou is still in memory, but after a period of time, because the string is not referenced by the variable, it will be recycled as garbage. Thus freeing up the block of memory.

Thus we come to the conclusion that the values of the original type are fixed, while the object type is composed of key-value pairs of the original type into a complex object. The value of the original type is directly stored in the stack memory, while the actual value of the object type is stored in the heap memory, and a reference address is saved in the stack memory. This address points to the actual value in the heap memory, so the object type is used to be called the reference type.

Ask the question why the value of the reference type is stored in heap memory. Can you save it in stack memory? Answer 1: because the size of the reference type is not fixed, the size of the stack is fixed, and the size of the heap space can be changed dynamically, so the value of the reference type is suitable to be stored in the heap; answer 2: when the execution context needs to be switched frequently during code execution, if the value of the reference type is stored in the stack, it will cause a lot of memory overhead.

Compare

When we compare two variables, different types of variables behave differently:

Let str1 = 'hello'let str2 =' hello'console.log (str1 = str2) / / truelet person1 = {name: 'bubuzou'} let person2 = {name:' bubuzou'} console.log (person1 = person2) / / false

We define two string variables and two object variables. they all look exactly the same, but the string variables are equal and the object variables are not equal. This is because in JavaScript, prototype types compare values in the existing stack for equality, while reference types compare reference addresses in stack memory for equality.

Copy

When a variable is copied, there is also a difference between the original type and the reference type variable. Take a look at the following code:

Let str1 = 'hello'let str2 = str1str2 =' world'console.log (str1) / / 'hello'

Before letstr1='hello': is copied, a variable str1 is defined and assigned a value of hello. At this time, the string hello will be allocated a piece of space in the stack memory for storage, and then the variable str1 will point to this memory address.

Letstr2=str1: after copying, assign the value of str1 to str2. At this time, a new space will be opened up in the stack to store the value of str2.

If str2='world': assigns a new string world to str2, a new block of memory will be created to store world. At the same time, the memory space of str2's original value hello will be treated as garbage collection after a period of time because there is no variable reference.

Console.log (str1): because the stack memory addresses of str1 and str2 are not the same, even if the value of str2 is changed, str1 will not be affected.

Then let's move on and look at the replication of the reference type:

Let person1 = {name: 'bubuzou', age: 20} let person2 = person1person2.name =' bubuzou.com'console.log (person1.name) / / 'bubuzou.com'

When the original type is copied, the value of the variable is re-assigned, as shown in the figure above: when the reference type is copied, the reference address pointed to by the variable is assigned to the new variable, so both person1 and person2 point to the same value in the heap memory, so when the person2.name is changed, the person1.name will also be changed.

Value passing and reference passing

Let's start with the conclusion that in JavaScript, the arguments of all functions are passed by value. Look at the following code:

Let name = 'bubuzou'function changeName (name) {name =' bubuzou.com'} changeName (name) console.log (name) / / 'bubuzou'

A variable name is defined and assigned to bubuzou, and name is passed when the function is called. At this time, a local variable name is created inside the function and the global variable value bubuzou is passed to him. This operation actually creates a new space in memory to store the value of the local variable, and then changes the value of the local variable to bubuzou.com At this time, there will be three address spaces in memory to store the value bubuzou of the global variable, the original value bubuzou of the local variable, and the new value bubuzou.com of the local variable. Once the function call ends, the local variable will be destroyed, and after a period of time, because the new and old values of the local variable have no variable references, the two spaces will be reclaimed and released; so the value of the global name is still bubuzou.

Let's take a look at the passing parameters of the reference type. will it be different?

Let person = {name: 'bubuzou'} function changePerosn (person) {person.name =' bubuzou.com'} changePerosn (person) console.log (person.name) / / 'bubuzou.com'

When the reference type passes parameters to the function, the reference address will be copied to the local variable, so the global person and the local variable person inside the function point to the same heap address, so once one side changes, the other side will also be changed, so can we conclude that when the function passes parameters, if the parameter is a reference type, then it is a reference pass?

Modify the above example:

Let person = {name: 'bubuzou'} function changePerosn (person) {person.name =' bubuzou.com' person = {name: 'hello world'}} changePerosn (person) console.log (person.name) / /' bubuzou.com'

If person is passed by reference, it automatically points to a new object whose value is changed to hello world; in fact, the reference address of the global variable person has not changed from beginning to end, but the reference address of the local variable person has changed.

Null and undefined are foolishly confused?

Null is a primitive type in JavaScript, with only one value null, which represents special values such as none, null, unknown value, and so on. You can directly assign a variable to null:

Let s = null

Undefined, like null, is also a primitive type, indicating that a variable is defined but not assigned, then the value of the variable is undefined:

Let sconsole.log (s) / / undefined

Although you can directly assign a variable to undefined will not report an error, but in principle, if the value of a variable is uncertain or empty, it is more appropriate to directly assign a value to null, and it is not recommended to assign a value of undefined to the variable. Both null and undefined return false when making logical judgments:

Let a = null, bconsole.log (a? 'a': B? 'b':'c') / /'c'

Null becomes 0 when converted to a numeric type, and undefined becomes NaN:

Let a = null, bconsole.log (+ null) / / 0console.log (+ b) / / NaN know the new primitive type Symbol

The Symbol value represents a unique identifier and is a newly introduced primitive type in ES6. You can create an important value through Symbol (), or you can pass in a description value; its uniqueness is that even if you pass in the same description, they are not equal:

Let a = Symbol ('bubuzou') let b = Symbol (' bubuzou') console.log (a = b) / false global Symbol

Is it true that any two Symbol with the same description are not equal? The answer is no. You can find or create a new Symbol through Symbol.for ():

Let a = Symbol.for ('bubuzou') let b = Symbol.for (' bubuzou') console.log (a = = b) / / true

Using Symbol.for (), you can look at the global scope based on the description passed in, create a new Symbol if not found, and return; so when you execute the second line of code Symbol.for ('bubuzou'), you will find the global Symbol described as bubuzou, so here an and b are absolutely equal.

It turns out that Symbol can be found through description, so can description be found through Symbol? The answer is yes, but it must be a global Symbol. If it is not found, undefined will be returned:

Let a = Symbol.for ('bubuzou') let desc = Symbol.keyFor (a) console.log (desc) / /' bubuzou'

But for any Symbol, there is an attribute description that represents the description of the Symbol:

Let a = Symbol ('bubuzou') console.log (a.description) / /' bubuzou'Symbol as object attribute

We know that the property key of an object can be a string, but it cannot be Number or Boolean; Symbol. In fact, the biggest original intention is to use the property key for the object:

Let age = Symbol ('20') let person = {name:' bubuzou', [age]:'20 characters, / / use square brackets when using `Symbol` in literal quantities of objects}

Here, person is defined with a Symbol as the property key. What is the advantage of this compared to using a string as the property key? The most obvious advantage is that if the person object is developed and maintained by multiple developers, it is easy to add attributes of the same name to the person. If you use a string as a property key, it must be a conflict, but if you use Symbol as a property key, there will be no problem, because it is a unique identifier, so you can protect the properties of the object from accidental access or rewriting.

Note that if you use Symbol as the property key of an object, the forin, Object.getOwnPropertyNames, or Object.keys () loop cannot get the Symbol property key, but it can be obtained through Object.getOwnPropertySymbols (); based on the above code:

For (let o in person) {console.log (o) / / 'name'} console.log (Object.keys (person)) / / [' name'] console.log (Object.getOwnPropertyNames (person)) / / ['name'] console.log (Object.getOwnPropertySymbols (person)) / / [Symbol (20)] types of Number that you may not know

There are two types of numbers in JavaScript: one is the Number type, which is stored in a 64-bit format IEEE-754, also known as a double-precision floating-point number, which ranges from $2 ^ {52} $to-$2 ^ {52} $; the second type is BigInt, which can represent integers of any length, including numbers beyond the range of $2 ^ {52} $to-2 ^ {52} $. Here we will only introduce Number numbers.

Regular and special numbers

For a regular number, we can write it directly, such as:

Let age = 20

But there is also a particularly high-digit number that we are used to using scientific notation to write:

Let billion = 1000000000X let b = 1e9

The above two words mean the same thing. 1e9 means 1 x $10 ^ 9 $; if it is 1e-3, it means 1 / $10 ^ 3 $= 0.001. Different digits can also be represented in JavaScript. For example, 10 in decimal can be represented as 0b1010, 0o12, and 0xa in binary, octal, and hexadecimal, respectively, where 0b is the binary prefix, 0o is the octal prefix, and ox is the hexadecimal prefix.

We can also use the toString (base) method to convert between digits. Base is the cardinality of the base, which represents decimal by default, and returns a string representation of the converted value. For example:

Let num = 10console.log (num.toString (2)) / / '1010'console.log (num.toString (8)) / /' 12'console.log (num.toString (16)) / /'a'

Numbers can also directly call methods, 10..toString (2) here 2. The number is not a mistake, but must be 2, otherwise a SyntaxError error will be reported. The first point represents the decimal point, and the second is the calling method. Dot symbols are first considered as part of a numeric constant, and then as property accessors. If only one dot is written, the computer cannot know whether this represents a decimal or to call a function. Functions called directly by numbers can also be written in the following ways:

(10) .toString (2) / / enclose 10 in parentheses 10.0.toString (2) / / write 10 in the form 10.0. ToString (2) / / call with dots and spaces

In addition to regular numbers, the Number type also contains some special numbers:

NaN: indicates that it is not a number, but is usually the result of unreasonable calculations, such as dividing the number by the string 1 Universe; NaN returns false when comparing with any number, including himself: NaN==NaN returns false;. How can you tell if a number is NaN? There are four ways:

Method 1: through the isNaN () function, this method will also return true for the passed string, so the judgment is not accurate and it is not recommended:

IsNaN (1 /'a') `/ / trueisNaN ('a') / / true

Method 2: through Number.isNaN (), it is recommended that:

Number.isNaN (1 /'a') `/ / trueNumber.isNaN ('a') / / false

Method 3: through Object.is (ameme isNaN):

Object.is (NaN) / / trueObject.is ('AFP, NaN) / / false

Method 4: if true is returned by judging the error error n, then n is NaN:

Let s = 1/'a'console.log (s! = s) / / true

+ Infinity: represents positive infinity, such as the result of the calculation of 1 Infinity 0, and-infinity represents negative infinity, such as the result of-1 prime 0.

+ 0 and-0, the numbers in JavaScript are both positive and negative, including zero, and they will be absolutely equal:

Console.log (+ 0 = =-0) / / true Why 0.1 + 0.2 is not equal to 0.3console.log (0.1 + 0.2 = = 0.3) / / false

Have you ever wondered why the upper ones are not equal? Because numbers are stored in binary within JavaScript, it follows the IEEE754 standard, using 64 bits to store a number, which is separated into 1, 11 and 52 bits to represent symbol bits, exponential bits and Mantissa bits, respectively.

For example, how much is the decimal 0.1 converted to binary? Let's calculate manually that the rule of decimal to binary decimal is "rounded by 2, arranged in order". The specific method is: with 2 times decimal, you can get the product, take out the integer part of the product, and then multiply the rest of the decimal part with 2. Get another product, and then take out the integer part of the product, so on, until the decimal part of the product is zero, or until the required precision is reached.

0.1 * 2 = 0.2 / / step 1: integer 0, decimal 0.20.2 * 2 = 0.4 / / step 2: integer 0, decimal 0.40.4 * 2 = 0.8 / / step 3: integer 0, decimal 0.80.8 * 2 = 1.6 / / step 4: integer 1, decimal 0.6 * 2 = 1.2 / / step 5: integer 1 Decimal 0.20.2 * 2 = 0.4 / / step 6: integer 0, decimal 0.40.4 * 2 = 0.8 / / step 7: integer 0, decimal 0.8.

After calculating in this way, we find that the order of integers is 0001100110011001100. Infinite loop, so in theory, the decimal 0.1 converted to binary will be an infinite decimal 0.0001100110011001100. When expressed by scientific counting, it will be 1.100110011001100. X $2 ^ {- 4} $, but because the IEEE754 standard stipulates that the number of bits stored in a number can only be 64 bits and the number of significant digits is 52 bits, it will be used for 11001100110011001100. This infinite number rounds a total of 52 bits as significant bits, and then the final binary trade-off rule is to look at the last digit if it is 1 carry, and if it is 0, it is directly rounded off. So because 1100110011001100. The 53rd digit of this string of numbers happens to be 1, so the final number is 11001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001100110011001101 x $2 ^ {- 4} $. Decimal to binary can also be converted using toString:

Console.log (0.1.toString (2)) / / '0.00011001100110011001100110011001100110011001100110011001101'

We found that the decimal 0.1 lost its precision when converted to a binary decimal, and it was larger than the real value due to rounding. In fact, 0.2 also has the same problem, and the loss of accuracy will also occur, so in fact, 0.1-0.2 will not be equal to 0.3:

Console.log (0.1 + 0.2) / / 0.300000000000004

Is there no way to tell whether two decimals are equal? The answer is definitely no. To determine whether two decimals N1 and N2 are equal, you can do the following:

Method 1: if the absolute value of the difference between two decimals is smaller than Number.EPSILON, then the two numbers are equal.

Number.EPSILON is the error precision in ES6, and the actual value can be considered to be equal to $2 ^ {- 52} $.

If (Math.abs (N1-N2)

< Number.EPSILON ) { console.log( 'n1 和 n2 相等' )} 方法二:通过 toFixed(n) 对结果进行舍入, toFixed() 将会返回字符串,我们可以用 一元加 + 将其转成数字: let sum = 0.1 + 0.2console.log( +sum.toFixed(2) === 0.3 ) // true数值的转化 对数字进行操作的时候将常常遇到数值的舍入和字符串转数字的问题,这里我们巩固下基础。先来看舍入的: Math.floor(),向下舍入,得到一个整数: Math.floor(2.2) // 2Math.floor(2.8) // 2 Math.ceil(),向上舍入,得到一个整数: Math.ceil(2.2) // 3Math.ceil(2.8) // 3 Math.round(),对第一位小数进行四舍五入: Math.round(2.26) // 2Math.round(2.46) // 2Math.round(2.50) // 3 Number.prototype.toFixed(n),和 Math.round() 一样会进行四舍五入,将数字舍入到小数点后 n 位,并且以字符串的形式返回: 12..toFixed(2) // '12.00'12.14.toFixed(1) // '12.1'12.15.toFixed(1) // '12.2' 为什么 6.35.toFixed(1) 会等于 6.3 ?因为 6.35 其实是一个无限小数: 6.35.toFixed(20) // "6.34999999999999964473" 所以在 6.35.toFixed(1) 求值的时候会得到 6.3。 再来看看字符串转数字的情况: Number(n) 或 +n,直接将 n 进行严格转化: Number(' ') // 0console.log( +'') // 0Number('010') // 10console.log( +'010' ) // 10Number('12a') // NaNconsole.log( +'12a' ) // NaN parseInt(),非严格转化,从左到右解析字符串,遇到非数字就停止解析,并且把解析的数字返回: parseInt('12a') // 12parseInt('a12') // NaNparseInt('') // NaNparseInt('0xA') // 10,0x开头的将会被当成十六进制数 parseInt() 默认是用十进制去解析字符串的,其实他是支持传入第二个参数的,表示要以多少进制的 基数去解析第一个参数: parseInt('1010', 2) // 10parseInt('ff', 16) // 255 如何判断一个数是不是整数?介绍两种方法: 方法一:通过 Number.isInteger(): Number.isInteger(12.0) // trueNumber.isInteger(12.2) // false 方法二: typeofnum=='number'&&num%1==0 function isInteger(num) { return typeof num == 'number' && num % 1 == 0}引用类型 除了原始类型外,还有一个特别重要的类型:引用类型。高程里这样描述他:引用类型是一种数据结构, 用于将数据和功能组织在一起。到目前为止,我们看到最多的引用类型就是 Object,创建一个 Object 有两种方式: 方式一:通过 new 操作符: let person = new Object()person.name = 'bubuzou'person.age = 20 方式二:通过对象字面量,这是我们最喜欢用的方式: let person = { name: 'bubuzou', age: 20}内置的引用类型 除了 Object 外,在 JavaScript 中还有别的内置的引用类型,比如: Array 数组 Date 日期 RegExp 正则表达式 Function 函数 他们的原型链的顶端都会指向 Object: let d = new Date()console.log( d.__proto__.__proto__.constructor ) // ƒ Object() { [native code] }包装类型 先来看一个问题,为什么原始类型的变量没有属性和方法,但是却能够调用方法呢? let str = 'bubuzou'str.substring(0, 3) // 'bub' 因为 JavaScript 为了更好地操作原始类型,设计出了几个对应的包装类型,他们分别是: Boolean Number String 上面那串代码的执行过程其实是这样的: 创建 String 类型的一个实例; 在实例上调用指定的方法; 销毁这个实例 用代码体现一下: let str = newString('bubuzou')str.substring(0, 3)str = null 原始类型调用函数其实就是自动进行了装箱操作,将原始类型转成了包装类型,然后其实原始类型和包装类型是有本质区别的,原始类型是原始值,而包装类型是对象实例: let str1 = 'bubuzou'let str2 = new String('bubuzou')console.log( str1 === str2 ) // fasleconsole.log( typeof str1 ) // 'string'console.log( typeof str2 ) // 'object' 居然有装箱操作,那肯定也有拆箱操作,所谓的拆箱就是包装类型转成原始类型的过程,又叫 ToPromitive,来看下面的例子: let obj = { toString: () =>

{return 'bubuzou'}, valueOf: () = > {return 20},} console.log (+ obj) / / 20console.log (`${obj}`) / /' bubuzou'

During the unpacking operation, the toString () and valueOf () methods of the wrapper type are tried by default. The order of hint calls varies. If hint is string, toString () will be called first, otherwise, valueOf () will be called first. By default, an Object object has toString () and valueOf () methods:

Let obj = {} console.log (obj.toString ()) / /'[object Object] 'console.log (obj.valueOf ()) / / {}, valueOf returns the type replacement of the object itself

Javascript is a weak type of speech, so type conversions often occur when operating on variables, especially implicit type conversions, which may surprise the execution results of the code, such as the following code, can you understand the execution results?

[] + {} / /'[object Object]'{} + [] / / 0 type conversion rules

So we need to know the rules of type conversion, here is a table listing the common values and types and the results after conversion, for reference only.

Display type conversion

When we write code, we should try our best to make the code easy to understand, so that others can read it and know what you are going to do, so we should try to show it when judging the type. For example, to convert a string into a number, you can do this:

Number ('21') / / 21Number (' 21.8') / / 21.8 percent 21 / 21

You can convert a number display to a string like this:

String (21) / / '21'21..toString () / /' 21'

The display can be converted to a Boolean type like this:

Boolean ('21') / / trueBoolean (undefined) / / falsehood. Nan / / falsehood. / / true.

In addition to the above, there are some unpopular operations about type conversion that sometimes work: directly use the unary plus operator to get the number of milliseconds of the current time:

+ new Date () / / 1595517982686

Use ~ with indexOf () to convert the operation result directly to Boolean type:

Let str = 'bubuzou.com'if (~ str.indexOf (' .com')) {console.log ('str prints this sentence if it contains a .com string')}

Use ~ ~ to intercept integers for characters or numbers, which is slightly different from Math.floor ():

~ 21.1 / / 21 implicit type conversions: 1.2a' / / 0Math.floor / / 21Math.floor (- 21.9) / /-22

Implicit type conversions occur at run time of JavaScript and are usually caused by certain operators or statements, as follows:

Implicitly convert to Boolean type:

If (..) The conditional judgment expression in the statement.

For (..;..) The conditional judgment expression in the statement (the second).

While (..) And do..while (..) The conditional judgment expression in the loop.

The conditional judgment expression in?:

The Operand to the left of the logical operators | (logical OR) and & & (logical and) (as a conditional expression)

If (42) {console.log (42)} while ('bubuzou') {console.log (' bubuzou')} const c = null? "exist": "does not exist" / / "does not exist"

The non-Boolean value in the above example is implicitly cast to a Boolean value to perform conditional judgment. Special attention should be paid to the | and & & operators. | | the operation procedure is that the right side is evaluated and returned as the final result only when the value on the left returns false, which is similar to the effect of a?a:b:

Const a ='a' | |'b' / / 'a'const b =''| |'c' / /'c'

The operation procedure of & & is to evaluate the right side only when the left value returns true and return the right value as a result, similar to the effect of a?b:a:

Const a ='a'& &'b'/ / 'b'const b =''& &'c'/ /''

The mathematical operator-* / converts to a numeric type first for non-numeric types, but is special for the + operator:

When one side is of String type, it is recognized as string concatenation, and the other side will be converted to string type first.

When the Number type is on one side and the primitive type on the other, the original type is converted to the Number type.

When there is a Number type on one side and a reference type on the other, convert the reference type and Number type to a string and concatenate it.

42 + 'bubuzou' / /' 42bubuzou'42 + null / / 4242 + true / / 4342 + [] / /'42 object Object 42 + {} / / 42 [object Object]'

Loose equality and strict equality

Loose equality (=) and strict equality (= =) are often asked during interviews, and the answer is generally = = to determine whether the values are equal, and to judge whether the types are equal in addition to judging whether the values will be equal or not. this answer is not entirely correct, the better answer is: implicit type conversion is allowed during the comparison process, and = = no. So how is the type conversion done?

1. Compare the number to the string, and the string will be converted into a number for comparison:

20 = = '20' / / true20 =' 20' / / false

2. Compared with other types, the Boolean type will first be converted to a number for comparison, true to the number 1, and false to the number 0. Note that this is a very error-prone point:

'bubuzou' = = true / / false'0' = = false / / truenull = = false / / false,undefined = = false / / false [] = true / / false [' 1'] = = true / / true

Therefore, when writing code to judge, you must not write x==true or x==false, but should directly if (x) judgment.

3. Null and undefined: the comparison result of null==undefined is true, except that the comparison value of null, undefined, and any other results is false. It can be considered that null and undefined can implicitly type convert each other in the case of = =.

Null = = undefined / / truenull = ='/ / falsenull = = 0 / / falsenull = = false / / falseundefined = ='/ / falseundefined = = 0 / / falseundefined = = false / / false

4. Comparing the original type with the reference type, the reference type will first ToPromitive into the original type and then make a comparison. The rules refer to the unpacking operation described above:

'42' = = [42] / / true'1,2,3' = = [1 undefined] / / true' [object Object]' = = {} / / true0 = = [undefined] / / true

5. Special value

NaN = = NaN / / false+0 = =-0 / / true [] =! [] / TrueMagi! [] has a high priority ratio, so! [] first converts to a Boolean value and becomes false;, then to the number 0, and [] to the number 0, so [] =! [] 0 = ='\ n'/ / true type detection uses typeof to detect the original type.

There are six primitive types in JavaScript, such as null, undefined, boolean, number, string and Symbol. We can use typeof to determine what primitive type the value is. A string representation of the type will be returned:

Typeof undefined / / 'undefined'typeof true / /' boolean'typeof 42 / / 'number'typeof "42" / /' string'typeof Symbol () / / 'symbol'

But there is an exception in the primitive type, typeofnull will get 'object', so when we use typeof to determine the type of the original value, we can not get an accurate answer, so how to determine whether a value is of type null?

Let o = nullroomo & & typeof o = = 'object' / / used to determine whether o is a null type

What's the difference between undefined and undeclared? The former represents variables that are defined but not assigned in scope, while the latter represents variables that are not defined in scope; undefined is undefined and undeclared is not declared.

Typeof can judge the original type, but can it also determine the reference type?

Typeof [] / / 'object'typeof {} / /' object'typeof new Date () / / 'object'typeof new RegExp () / /' object'typeof new Function () / / 'function'

From the above results, we can draw a conclusion: when typeof judges the reference type, only the function type can correctly judge, and none of the others can correctly judge what the reference type is.

Use instanceof to detect reference types

We know that typeof can only detect some primitive types, and there is nothing we can do about reference types. JavaScript provides an operator instanceof, and let's see if he can detect reference types:

[] instanceof Array / / true [] instanceof Object / / true

We find that the array is both an instance of Array and an instance of Object, because the end point of the reference type prototype chain is Object, so Array is naturally an instance of Object. So we conclude that instanceof does not seem to be a very reliable choice for detecting reference types.

Type checking with toString

We can use Object.prototype.toString.call () to detect the type of value of any variable:

Object.prototype.toString.call (true) / /'[object Boolean] 'Object.prototype.toString.call (undefined) / /' [object Undefined] 'Object.prototype.toString.call (null) / /' [object Null] 'Object.prototype.toString.call (20) / /' [object Number] 'Object.prototype.toString.call (' bubuzou') / /'[object String] 'Object.prototype.toString.call (Symbol ()) / / [ Object Symbol] 'Object.prototype.toString.call ([]) /' [object Array] 'Object.prototype.toString.call ({}) / /' [object Object] 'Object.prototype.toString.call (function () {}) / /' [object Function] 'Object.prototype.toString.call (new Date ()) / /' [object Date] 'Object.prototype.toString.call (new RegExp ()) / /' [object RegExp] 'Object.prototype. ToString.call (JSON) / /'[object JSON] 'Object.prototype.toString.call (MATH) / /' [object MATH] 'Object.prototype.toString.call (window) / /' [object RegExp] 'what are the knowledge points of JS data types? Thank you for your reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report